function xc=bisect(f,a,b,tol) % Bisection Method, xc=bisect(f,a,b,tol) % Computes an approximation to f(x)=0 given that the % root is bracketed in [a,b] with f(a)f(b)<0. Will run % until TOL is reached, and will output the solution xc. % % EXAMPLE: f=inline('x^3+x-1'); % xc=bisect(f,0,1,0.00005); %Error check and initialization: fa=feval(f,a); fb=feval(f,b); if sign(fa)*sign(fb)>=0 error('Root may not be bracketed'); end iter=0; while (b-a)/2>tol iter=iter+1; c=(a+b)/2; fc=feval(f,c); if fc==0 %This means that (a+b)/2 is the root- break %Break out of the while loop and %continue execution end if sign(fc)*sign(fa)<0 %New interval is [a,c] (reset b) b=c; fb=fc; else a=c; fa=fc; %New interval is [c,b] (reset a) end end fprintf('Finished after %d iterates\n',iter); xc=(a+b)/2;