Skip to content

Instantly share code, notes, and snippets.

@Ming-Tang
Created November 24, 2010 04:17
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 Ming-Tang/713104 to your computer and use it in GitHub Desktop.
Save Ming-Tang/713104 to your computer and use it in GitHub Desktop.
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