Last active
May 26, 2020 20:40
-
-
Save tswedish/4b711a7b8f8192f9160f7d16295a4b9a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Dual: | |
def __init__(self, value=0., derivative=0.): | |
self.value = value | |
self.derivative = derivative | |
def __add__(self, other): | |
return Dual(self.value + other.value, self.derivative + other.derivative) | |
def __mul__(self, other): | |
return Dual(self.value * other.value, self.value*other.derivative + self.derivative * other.value) | |
def __pow__(self, other): | |
if self.value > 0.: | |
return Dual(self.value**other.value, self.derivative * other.value * self.value**(other.value-1) + other.derivative * self.value**other.value * math.log(self.value)) | |
else: | |
return Dual(self.value**other.value, self.derivative * other.value * self.value**(other.value-1)) | |
def __truediv__(self, other): | |
return self * other**(-1.) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment