Created
November 24, 2010 04:17
-
-
Save Ming-Tang/713104 to your computer and use it in GitHub Desktop.
Square root using Newton's Method
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
#!/usr/bin/python | |
def sqrt_newton(x): | |
if abs(x) > 1e16: raise ValueError("Too large to be calculated accurately.") | |
f = lambda a: a ** 2 - x | |
f1 = lambda a: 2.0 * a | |
x1 = x / 2.0 | |
dx = 1e-16 * 10.0 ** (len(repr(x)) * 1.0) | |
while abs(f(x1)) > dx: | |
x1 = x1 - (f(x1) / f1(x1)) | |
return x1 | |
if __name__ == "__main__": | |
print [(sqrt_newton(10 ** x * 1.0), sqrt_newton(10 ** x * 5.0) ** 2.0) for x in range(1, 16)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment