Last active
May 18, 2019 07:56
-
-
Save swuecho/8e2ddaf31bdae7e30d1f758c235ff97a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# modified from the python code in | |
# https://pizzaseminar.speicherleck.de/automatic-differentiation/notes.pdf | |
class Dual(object): | |
def __init__(self, x, a=0): | |
self.x = x | |
self.a = a | |
def __add__(self, other): | |
return Dual(self.x + other.x, self.a + other.a) | |
def __mul__(self, other): | |
return Dual(self.x * other.x, | |
other.x * self.a + self.x * other.a) | |
def __truediv__(self, other): | |
return Dual(self.x / other.x, | |
(other.x * self.a - self.x * other.a)/other.x**2) | |
def babylonia_raw(x, N=10): | |
t = (1+x)/2 | |
for i in range(1, N): | |
t = (t+x/t)/2 | |
return t | |
def babylonia(x, N=10): | |
"""python do not have enough type infor to auto convert the type as | |
julia, so have to convert manually""" | |
t = (Dual(1)+x)/Dual(2) | |
for i in range(1, N): | |
t = (t+x/t)/Dual(2) | |
return t | |
if __name__ == "__main__": | |
x = babylonia(Dual(49, 1), 10).x | |
a = babylonia(Dual(49, 1), 10).a | |
print(x, a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment