function secant

f = @(x) exp(x)-2;
fp = @(x) exp(x);
xroot = log(2);

% f = @(x) x.^2;
% fp = @(x) 2*x;
% xroot = 0;
% 
% f = @(x) x.*(1-x).^2;
% fp = @(x) -2*x.*(1 - x) + (1-x).^2;
% xroot = 1;

tol = 1e-14;

x0 = .4;
[x,xhist] = newton(f,fp,x0,tol);
semilogy(abs(xroot-xhist),'o-')
hold on

x0 = .3;
x1 = .6;
[x,xhist] = secant_iter(f,x0,x1,tol);
xhist
semilogy(abs(xroot-xhist),'o-')

legend('Newton','Secant')

return


function [x,xhist] = secant_iter(f,x0,x1,tol)

f0 = f(x0);
f1 = f(x1); % evaluate f at the bracket endpoints
k = 0;
maxit = 100;

while (abs(f1)>tol) && (k < maxit)
    fprintf('Secant error at iterate %3d: %20.14f %10.7e\n', k, x0, f(x0));
    x = x1 - f1*(x1-x0)/(f1-f0); % generate new root estimate
    x0 = x1; f0 = f1;
    x1 = x;  f1 = f(x1);
    k = k+1;
    xhist(k) = x;
end
x = x1;



function [x0,xhist] = newton(f, fp,x0,tol)

maxit = 100;

k = 1;
while (abs(f(x0))>tol && (k<maxit))
    fprintf('Newton error at iterate %3d: %20.14f %10.7e\n', k, x0, f(x0));
    x0 = x0 - f(x0)/fp(x0);
    xhist(k) = x0;
    k = k+1;
end

xhist(k) = x0;

return
