function [ root ] = binarySearchV2( func, xlow, xhigh, tol ) %binarySearchV2 method to find root of a function (called func) % this is just like binarySearch but it evaluates func fewer times % it also checks that there is a root in the initial interval % Use this to solve exp(x) - 4x == 0 by running % binarySearchV2( @(x) exp(x)-4*x, 0,1, 1e-7) a=xlow; b=xhigh; fa = func(a); fb = func(b); if ( fa*fb > 0 ) error('f(a).f(b) must be < 0 for bisection') end while abs(b - a)/2 > tol*abs(a+b)/2 c = (a+b)/2; fc = func(c); % only one evaluation of f per loop if fb*fc > 0 b = c; fb = fc; else a = c; % (fb stays the same) end end % of the "while loop" root = (a+b)/2; end % of the function