You are on page 1of 2

function [xr, ea] = bisect(xl, xu, es, imax)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% This function implements the bisection algorithm for finding roots
% of equation in single variable
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Syntax: [xr, ea] = bisect(xl, xu, es, imax)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Input(s):
% xl = Lower guess
% xu = Upper guess
% es = Percentage value of error tolerance
% imax = Maximum number of iterations
% Output(s):
% xr = Estimated value of root at last iteration
% ea = Percentage relative approximate error at last iteration
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Initialize iteration counter
iter = 0;
%old estimate of root is unknown
xrold = Inf;
%display string
disp(' iteration xl xu xr f(xl) f(xu) f(xr) ea(%)');
while (1)
%Bisection method
xr = (xl + xu)/2;
%compute percentage relative approximate error
if(xr ~= 0)
ea = abs( (xr - xrold) / xr)* 100;
end
%display some results
disp([iter, xl, xu, xr, func(xl), func(xu), func(xr), ea]);
%test each interval for root and update xl and/or xu.
test = func(xl)*func(xr);
if(test < 0)
xu = xr;
elseif(test > 0)
xl = xr;
else
ea = 0;
end
%update old estimate of the root
xrold = xr;
%update the iteration counter
iter = iter + 1;
%terminate the loop if solution is found
if( (ea < es) || (iter >= imax))
break;
end
end

You might also like