%estimates a root of f via the secant method
%original method is modified to avoid dividing by zero

format long;

f = @(x) x^3+2*x+cos(x);
phi = @(x,y) x-f(x)*(x-y)/(f(x)-f(y));

tol = 10^(-9);  %algorithm stops when |f(new guess)-f(old guess)|<=tol
x_old = 1;      %first guess
x_new = 0.9;    %second guess


while abs(f(x_new)-f(x_old))>tol
    x = phi(x_new,x_old); 
    x_old = x_new;
    x_new = x;
end             %can you identify a possible problem with this while loop?

disp('estimate of root is...')
x_new

disp('true value is...')
-0.419659764448812