% % In this example, we use the bisection method to solve % cos x - x = 0 % % Set a, b, TOL, N a = 0; b = pi/2; TOL = 1e-8; N = 100; % Set the iteration index i = 1; % Start the iteration while ( i<=N & b-a>2*TOL ) i = i+1; p = (a+b)/2; if (cos(a)-a)*(cos(p)-p)>0 a = p; else b = p; end end % Print the result if ( b-a<2*TOL ) fprintf('Found the root %12.10f after %d iterations.\n', p, i-1); else fprintf('Method failed after %d iterations', i); end
Found the root 0.7390851380 after 27 iterations.