function [a,b,fail] = bisect(f,a,b,eps,N) % % Applies the bisection method to the function f on [a,b], % f is assumed to be continuous and f(a)*f(b) < 0. % Stops when |f(a)| < eps or |f(b)| < eps or |b-a| < eps. % Failure is reported (fail = 1) when the accuracy requirement % is not satisfied in N steps; otherwise fail = 0 on return. % % Example : % >> [a,b,fail] = bisect('cos',pi/4,2*pi/3,1.0e-4,100) % fprintf('running the bisection method...\n'); fprintf('-------------------------------------------\n'); fprintf(' a b m |f(m)| |b-a| \n'); fprintf('-------------------------------------------\n'); for i = 1:N m = (a+b)/2; fm = feval(f,m); if fm*feval(f,a) < 0 b = m; else a = m; end; fprintf(' %4.3f %4.3f %4.3f %.2e %.2e\n',a,b,m,abs(fm),abs(b-a)); if (abs(fm) < eps) | ((b-a) < eps) fail = 0; fprintf('succeeded after %d steps\n', i); return; end end fprintf('failed requirements after %d steps\n', N); fail = 1;