% this code finds roots of functions using bisection

function bisect_function
% guess a lower bound
a = 0;

% guess an upper bound
b = 10;

%this is the answer - call the function bisect(a,b)

r = bisect(a,b)



function root = bisect(a,b)

ul = a;
fl = feval(ul);
uu = b;
fu = feval(uu);

% we make the assumption, without checking, that 
% fu*fl<0

% if not, the algoritm fails to find a root.

N = 20;  % number of iterates
% the main bisection algorithm
for j = 1:N
u = (ul+uu)/2;
fc = feval(u);
ftest = (fc*fl>=0);
ul = ftest*u+(1-ftest)*ul;
fl = ftest*fc + (1-ftest)*fl;

uu = (1-ftest)*u+ ftest*uu;
fu = (1-ftest)*fc + ftest*fu;
end
root = u;

function f = feval(u)
% evalute the function
% put the function of your choice here
f = 1-u;
