% Bisection method example: use the bisection method to solve f(x) = 0
tic
xL    = 0;
xH    = 1;
xroot = xH;
e     = 0.001;

N = 0;

converged_flag = 0;


while converged_flag == 0
    N = N+1;
    
    % step 2
    xrootlast = xroot;
    xroot     = 0.5*(xL + xH);  
    
    % step 3
    if f(xroot) == 0
        converged_flag = 1;
        
    elseif f(xL)*f(xroot) < 0
        xH = xroot;
    else
        xL = xroot;
    end
    
    % step 4
%     if abs(f(xroot)) < e & abs(xroot - xrootlast) < e
%         converged_flag = 1;
%     end
    if abs(xroot - xrootlast) < e
        converged_flag = 1;
    end
    
end

xroot
toc