MCPcopy Create free account
hub / github.com/subbarayudu-j/TheAlgorithms-Python / newton_raphson

Function newton_raphson

maths/newton_raphson.py:20–40  ·  view source on GitHub ↗
(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6,logsteps=False)

Source from the content-addressed store, hash-verified

18 return (f(a+h)-f(a-h))/(2*h)
19
20def newton_raphson(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6,logsteps=False):
21
22 a = x0 #set the initial guess
23 steps = [a]
24 error = abs(f(a))
25 f1 = lambda x:calc_derivative(f, x, h=step) #Derivative of f(x)
26 for _ in range(maxiter):
27 if f1(a) == 0:
28 raise ValueError("No converging solution found")
29 a = a - f(a)/f1(a) #Calculate the next estimate
30 if logsteps:
31 steps.append(a)
32 error = abs(f(a))
33 if error < maxerror:
34 break
35 else:
36 raise ValueError("Itheration limit reached, no converging solution found")
37 if logsteps:
38 #If logstep is true, then log intermediate steps
39 return a, error, steps
40 return a, error
41
42if __name__ == '__main__':
43 import matplotlib.pyplot as plt

Callers 1

newton_raphson.pyFile · 0.85

Calls 3

calc_derivativeFunction · 0.85
f1Function · 0.85
fFunction · 0.70

Tested by

no test coverage detected