function combo

%  Solves  f(x) = 0  using the bisection, newton, and secant methods

%  Input:
%	a0 = first starting point
%	b0 = second starting point
%	tol = tolerance for stopping
%	f(x) and df(x) These are at end of file

a0=0;
b0=3;
tol=10^(-12);

% bisection method
a=a0;
b=b0;
if f(a)*f(b)>0
    error('Biesction interval incorrect')
end
mid=0.5*(a+b);
it=0;
err=3*tol;
while err>tol
    fmid=f(mid);
    if f(a)*fmid<0
        b=mid;
    elseif f(b)*fmid<0
        a=mid;
    else
        break
    end
    mid0=mid;
    mid=0.5*(a+b);
    err=abs(mid-mid0);
    it=it+1; error_b(it)=err;
end
bisection_iterations=it

% newton method
error_n=zeros(20,1);
xa=a0;
err=3*tol;
it=0;
while err>tol
    xb=xa-f(xa)/df(xa);
    err=abs(xb-xa);
    it=it+1; error_n(it)=err;
    xa=xb;
end

% secant method
xa=a0;  xb=b0;
fa=f(xa);
fb=f(xb);
err=3*tol;
it=0;
while err>tol
    xc=xb-fb*(xb-xa)/(fb-fa);
    err=abs(xc-xb);
    xa=xb;  fa=fb;
    xb=xc;  fb=f(xb);
    it=it+1; error_s(it)=err;
end
it_max=it;

% plot error curves
clf
% get(gcf)
set(gcf,'Position', [1 925 560 420])

for it=1:it_max
    semilogy(1:it,error_b(1:it),'--ok','LineWidth',1.5,'MarkerSize',8)
    hold on
    semilogy(1:it,error_n(1:it),'--ob','LineWidth',1.5,'MarkerSize',8)
    semilogy(1:it,error_s(1:it),'--or','LineWidth',1.5,'MarkerSize',8)
    xlabel('Iteration Step')
    ylabel('Iterative Error')
    grid on
    box on
    set(gca,'FontSize',16,'FontWeight','bold')
    axis([1 10 1e-15 10])
    hold off
    legend({' Bisection',' Newton',' Secant'},'Location','SouthWest','FontSize',16)
    pause
end



function g=f(x)
g=exp(1-2*x)-x;

function g=df(x)
g=-2*exp(1-2*x)-1;




