Write a script that starts with the definition of a function \(f\) and two initial points, for example
f = @(x) x^3 - x; x = 5; p = 7;
and proceeds to find a root of \(f\) using the secant method: the next point to be computed will be
\begin{equation*}
x - f(x) \frac{x-p}{f(x)-f(p)}
\end{equation*}
where the fraction represents division by the slope of secant line.
Solution.
f = @(x) x^3 - x;
x = 5;
p = 7;
max_tries = 1000
for k = 1:max_tries
x1 = x - f(x)*(x-p)/(f(x)-f(p));
if abs(x1-x) < 100*eps(x)
break
end
p = x;
x = x1;
end
if k < max_tries
fprintf('Found x = %.12g after %d steps\n', x, k);
else
disp('Failed to converge')
end
This script follows the structure of Example 8.2.1 except that we compute "new x", called x1, on the basis of two previous values (called
x and p). After the computation, x and p are replaced by x1 and x: the newly computed point becomes one of the two points through which we draw next secant line.
