Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Square root using Newton's Method
#!/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
You can’t perform that action at this time.