Skip to content

Commit cfde856

Browse files
authored
Create NewtonZeroFinder.py
Function to search the roots of a differentiable function with the Newton's method.
1 parent e8dce9b commit cfde856

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def find_zero_Newton(f,x0=1,df=None,dx=0.1,iterations=1000,precision=1e-7,epsilon=1e-15):
2+
"""
3+
Uses Newton's method to find a root near the given point x0.
4+
"""
5+
if df==None: # Aproximates the derivative if missing
6+
def derivative(x):
7+
return (f(x+dx)-f(x))/dx
8+
df = derivative
9+
sol = False
10+
for i in range(iterations):
11+
y, dy = f(x0), df(x0)
12+
if abs(dy) < epsilon: break
13+
14+
x1 = x0 - y/dy
15+
if abs(x1 - x0) <= precision*abs(x1):
16+
sol = True
17+
break
18+
x0 = x1
19+
if sol:
20+
print("Solution FOUND")
21+
return x1
22+
print("Solution NOT FOUND")

0 commit comments

Comments
 (0)