import numpy as np
import matplotlib.pyplot as pt
def f(x):
return np.exp(x) - 2
def df(x):
return np.exp(x)
xgrid = np.linspace(-2, 3, 1000)
pt.grid()
pt.plot(xgrid, f(xgrid))
What's the true solution of $f(x)=0$?
xtrue = np.log(2)
print(xtrue)
print(f(xtrue))
Now let's run Newton's method and keep track of the errors:
errors = []
x = 2
At each iteration, print the current guess and the error.
x = x - f(x)/df(x)
print(x)
errors.append(abs(x-xtrue))
print(errors[-1])
for err in errors:
print(err)
# Doubles number of digits each iteration: probably quadratic.
Let's check:
for i in range(len(errors)-1):
print(errors[i+1]/errors[i]**2)