% bisection method in order to find the root of the function f
% INPUT
% fun      function
% a    
% b        interval [a, b] of search
% err      error
  
% OUTPUT
% x0      root
% fx0     value of the function at x_0
% iter    number of iterations used 

function [x0, fx0, iter] = bisection(fun, a, b, err)
if fun(a)*fun(b)<0 
    % counter
    i=0;
    while abs(b-a)>2*err
        xm=(a+b)/2;
        if (fun(a)*fun(xm))>0
            %eliminate left half interval
            a=xm;
        else
            %eliminate right half interval
            b=xm;
        end
        i=i+1;
    end
    x0=xm;
    fx0=fun(x0);
    iter=i;
else
    print('choose different interval [a, b] such that f(a)*f(b)<0')
end