from math import exp, log
def f(x):
return x**exp(x) -2
def fp(x):
return exp(x) * x**(exp(x)-1) * (1+x*log(x))
def newton_raphson(x0, f, fp, eps, max_iter=100, show=False):
iter = 1
x = x0 - f(x0)/fp(x0)
if show:
print(' # | root')
print(f'{0:2} | {x0:.4f}')
print(f'{iter:2} | {x:.4f}')
while abs(x-x0) > eps:
iter += 1
if iter > max_iter:
print(f'Noconvertion in {max_iter} iterations')
break
x0 = x
x = x0 - f(x0)/fp(x0)
if show:
print(f'{iter:2} | {x:.4f}')
return x
newton_raphson(1, f, fp, 0.001, show=True)
# | root
0 | 1.0000
1 | 1.3679
2 | 1.2666
3 | 1.2294
4 | 1.2257
5 | 1.2257
Comments
Leave a comment