function bisection_visual(a,b,criterion,f)
%BISECTION_VISUAL(f,v)
%   Runs the bisection rootfinding algorithm for the function
%   f on the starting interval (a,b), using a stopping
%   criterion that can be specified. The iteration is
%   visualized graphically.
%
%   (C) 2010/09/21 by Steve Shank

if nargin<3
    criterion=1;
end
if nargin<4
    f=@(x) x.^3-5*x;
end

if abs(f(a))<10*eps
    error('Input argument a is a root!\n')
elseif abs(f(b))<10*eps
    error('Input argument b is a root!\n')
elseif f(a)*f(b)>0
    error('Function has same sign at endpoints... method is invalid!\n')
elseif b<=a
    error('Invalid interval parameters!')
end

tol=1e-5;
x=linspace(a,b);
y1=min(f(x));
y2=max(f(x));
x_approx=(a+b)/2;
condition=1;
iter=0;
close
while condition
    iter=iter+1;
    if abs( f(x_approx) ) < 10*eps
        fprintf('Got lucky and ran into a root on iterate %d: x=%.2e\n',iter,x_approx)
        return
    elseif f(a)*f(x_approx)<0
        b=x_approx;
    elseif f(x_approx)*f(b)<0
        a=x_approx;
    end
    x_approx=(a+b)/2;
    
    plot(x,f(x),'b',x,0,'k',x_approx,f(x_approx),'.r', ...
        a,0,'.k',b,0,'.k')
    axis([x(1) x(end) y1 y2])
    crit_1=abs( f(x_approx) );
    crit_2=(b-a)/2^iter;
    title(sprintf('First criterion:%.2e, second criterion:%.2e',crit_1,crit_2))
    drawnow
    pause(1)
    
    switch criterion
        case 1
            condition=abs( f(x_approx) ) > tol;
        case 2
            condition=(b-a)/2^iter > tol;
    end
    
    if iter==100
        break
    end
end

fprintf('After %d iterates, approximate solution is x=%.3e.\n',iter,x_approx)

