(f, x0=0, maxiter=100, step=0.0001, maxerror=1e-6,logsteps=False)
| 18 | return (f(a+h)-f(a-h))/(2*h) |
| 19 | |
| 20 | def 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 | |
| 42 | if __name__ == '__main__': |
| 43 | import matplotlib.pyplot as plt |
no test coverage detected