Given initial guess $x_0$, $x_1$, we find the next estimate by $$ x_2 = x_1 - f(x_1) \frac{x_1 - x_0}{f(x_1) - f(x_0)} $$ We iterate until $$ |x_2 - x_1| < |x_2| \epsilon $$ Let us find roots of $$ f(x) = \exp(x) - \frac{3}{2} - \arctan(x) $$
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
from numpy import exp, arctan, linspace, abs
import matplotlib.pyplot as plt
f = lambda x: exp(x) - 3.0/2.0 - arctan(x)
x = linspace(0.0, 1.0, 100)
plt.plot(x,f(x))
plt.grid(True)
M = 50 # maximum number of iterations
eps = 1.0e-6 # tolerance for stopping
x0, x1 = 0.5, 0.6
for i in range(M):
f0, f1 = f(x0), f(x1)
x2 = x1 - f1*(x1 - x0)/(f1 - f0)
if abs(x2-x1) < abs(x2)*eps:
break
print(i, x0, x1, f0, f1)
x0, x1 = x1, x2
print("Number of iterations = ", i)
print("Final solution = ", x2, f(x2))
0 0.5 0.6 -0.31492633830067795 -0.21830069988007528 1 0.6 0.8259241992584121 -0.21830069988007528 0.09364094333639517 2 0.8259241992584121 0.7581046067123907 0.09364094333639517 -0.014440726409248872 3 0.7581046067123907 0.7671659413813372 -0.014440726409248872 -0.0007430824196771324 4 0.7671659413813372 0.7676575090185478 -0.0007430824196771324 6.472411304581094e-06 Number of iterations = 5 Final solution = 0.7676532662012716 -1.1213252548714081e-14