Skip to content

Instantly share code, notes, and snippets.

@tswedish
Last active May 26, 2020 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tswedish/4b711a7b8f8192f9160f7d16295a4b9a to your computer and use it in GitHub Desktop.
Save tswedish/4b711a7b8f8192f9160f7d16295a4b9a to your computer and use it in GitHub Desktop.
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