function fig2_13

%  Solve  f(x) = 0  using bisection, Newton, and secant

% Solution of  exp(-x)-(2+x) = 0  to 20 digits:
%xe=-0.4428544010023885831;

tol=10^(-12);
a0=-2;
b0=0;

%%% bisection procedure
a=a0; b=b0;
mid=0.5*(a+b);
tolB=10^(-3);
err=10*tolB;
it=0;
while err>tolB
    old=mid;
    fmid=f(mid);
    if f(a)*fmid<0
        b=mid;
    elseif f(b)*fmid<0
        a=mid;
    else
        break
    end
    mid=0.5*(a+b);
    it=it+1;
    err=abs((mid-old)/mid);
    errB(it)=err;
end
it

%%% secant procedure
x=b0;
X=a0;
k=0;
err=10*tol;
while err>tol
    k=k+1;
    z=f(x)*(x-X)/(f(x)-f(X));
    X=x;
    x=x-z;
    err=abs(z/x);
    itS(k)=k+1;
    errS(k)=abs(z/x);
end
k

% newton
x=b0;
err=10*tol;
k=0;
while err>tol
    k=k+1;
    z=f(x)/df(x);
    x=x-z;
    err=abs(z/x);
    errN(k)=err;
end
k

clf
% get(gcf)
set(gcf,'Position', [25 1115 658 230])
subaxis(1,1,1,1,'MT',0.01,'MB',0.18,'MR',-0.02,'ML',0.06,'P',0.04)
co = [0 0 1;
    0 0.5 0;
    1 0 0;
    0 0.75 0.75;
    0.75 0 0.75;
    0.75 0.75 0;
    0.25 0.25 0.25];
set(groot,'defaultAxesColorOrder',co)

% plot error
semilogy(1:length(errB),errB,'--sk','LineWidth',1.5,'MarkerSize',8)
hold on
semilogy(itS,errS,'--*b','LineWidth',1.5,'MarkerSize',8)
semilogy(1:length(errN),errN,'--or','LineWidth',1.5,'MarkerSize',8)

legend({' Bisect',' Secant',' Newton'},'AutoUpdate','off','Location','SouthEast','FontSize',16,'FontWeight','bold')
axis([1 12  1e-16 10])
set(gca,'ytick',[1e-16 1e-12 1e-8 1e-4 1])
xlabel('k')
ylabel('Error')
grid on
box on
set(gca,'FontSize',16,'FontWeight','bold')

%exportgraphics(gcf,'/Users/mark/Desktop/compar.eps')


function g=f(x)
g=exp(-x)-2-x;

function g=df(x)
g=-exp(-x)-1;

