% 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,@fval)

r = bisect(a,b,@fval)

function root = bisect(a,b,feval)

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
uc = (ul+uu)/2;
fc = feval(uc);
ftest = (fc.*fl>0);
ul = ftest.*uc+(1-ftest).*ul;
fl = ftest.*fc + (1-ftest).*fl;

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

function f = fval(u)
% evaluate the function
% put the function of your choice here
% u is allowed to be a vector 
f = 1-2*u;

