function [ root ] = binarySearch( func, xlow, xhigh, tol )
%binarySearch method to find root of a function (called func)
% the output is root, initial guesses xlow and xhigh
% the tolerance (tol) is such that there is a root between
% xroot(1+tol) and xroot(1-tol), this is "relative error"
% (see lecture 3)
% Use this to solve exp(x) - 4x == 0 by running
% binarySearch( @(x) exp(x)-4*x, 0,1, 1e-7)
a=xlow;
b=xhigh;
while abs(b - a)/2 > tol*abs(a+b)/2
c = (a+b)/2;
if func(b)*func(c) > 0
b = c;
else
a = c; % (fb stays the same)
end
end % of the "while loop"
root = (a+b)/2;
end % of the function