Using the secant line

We return to finding a root of the equation \(xe^x=2\).

using Plots
f = x -> x*exp(x) - 2;

plot(f,0.25,1.25,label="function",leg=:topleft)

From the graph, it’s clear that there is a root near \(x=1\). To be more precise, there is a root in the interval \([0.5,1]\). So let us take the endpoints of that interval as two initial approximations.

x1 = 1;    f1 = f(x1);
x2 = 0.5;  f2 = f(x2);
scatter!([x1,x2],[f1,f2],label="initial points")

Instead of constructing the tangent line by evaluating the derivative, we can construct a linear model function by drawing the line between the two points \(\bigl(x_1,f(x_1)\bigr)\) and \(\bigl(x_2,f(x_2)\bigr)\). This is called a secant line.

slope2 = (f2-f1) / (x2-x1);
secant2 = x -> f2 + slope2*(x-x2);
plot!(secant2,0.25,1.25,label="secant line",l=:dash,color=:black)

As before, the next value in the iteration is the root of this linear model.

x3 = x2 - f2/slope2;
@show f3 = f(x3)
scatter!([x3],[0],label="root of secant")
f3 = f(x3) = -0.17768144843679456

For the next linear model, we use the line through the two most recent points. The next iterate is the root of that secant line, and so on.

slope3 = (f3-f2) / (x3-x2);
x4 = x3 - f3/slope3;
f4 = f(x4)
0.05718067370113333