-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterationNewton_method.py
45 lines (36 loc) · 984 Bytes
/
iterationNewton_method.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def improve(update, close, guess=1):
while not close(guess):
guess = update(guess)
return guess
def approx_eq(x, y, tolerance=1e-3):
return abs(x - y) < tolerance
def find_zero(f, df):
def near_zero(x):
return approx_eq(f(x), 0)
return improve(newton_update(f, df), near_zero)
def newton_update(f, df):
def update(x):
return x - f(x) / df(x)
return update
def square_root_newton(a):
def f(x):
return x * x - a
def df(x):
return x * x
return find_zero(f, df)
def nth_root_of_a (n, a):
def f(x):
return power(x, n) - a
def df(x):
return n * power(x, n -1)
return find_zero(f, df)
def power(x, n):
"""Return x * x * x *......* x for x repeated n time."""
product, k = 1, 0
while k < n:
product, k = product * x, k + 1
return product
print(square_root_newton(64))
print(nth_root_of_a(2, 64))
print(nth_root_of_a(3, 64))
print(nth_root_of_a(6, 64))