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,0.0001,100) % fprintf('running the bisection method...\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(' a = %f, b = %f, m = %f, f(m) = %f\n', a,b,m,fm); 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;