Created
September 12, 2018 03:57
-
-
Save pwxcoo/66c1e6220c79893383e22c95a2c7125e to your computer and use it in GitHub Desktop.
Newton Iteration Sqrt
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
def newtonSqrt(n, eps=1e-8): | |
""" | |
- ASSUME | |
f(x) = x^2 - n | |
when f(x)=0, x will be the root of n. | |
- DEDUCE BY Taylor Series Formula | |
f(x) = f(x0) + (x - x0)f'(x0) | |
- WHEN f(x)=0 | |
x = x0 - f(x0)/f'(x0) | |
x will be closer to the root than x0 | |
- DEDUCE | |
x(n+1) = xn - f(xn)/f'(xn) | |
- SIMPLIFY | |
x(n+1) = (xn + n/xn) / 2 | |
""" | |
root = n | |
while abs(root**2 - n) > eps: | |
lastVal = root | |
root = (root + n/root) / 2 | |
if abs(lastVal - root) <= eps: | |
break | |
return root | |
import random | |
eps = 1e-5 | |
for i in range(50): | |
num = random.randint(1, 1e9) | |
print(num) | |
assert num - newtonSqrt(num)**2 <= eps, f'failed when newtonSqrt({num})' | |
print('Accept') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment