function [x,fail] = secant(f,x1,x2,eps,N) % % Applies the secant method to the function f, starting % at the points x1 and x2. It produces a sequences of points. % Stops when the sequence reaches the point x where % |f(x)| < eps or when two consecutive points in the sequence % have distance less than eps apart from each other. % Failure is reported (fail = 1) when the accuracy requirement % is not satisfied in N steps; otherwise fail = 0 on return. % % Note that the implementation below is inefficient, as it does % not store the function evaluations. % % Example : % >> [x,fail] = secant('cos',pi/4,2*pi/3,0.0001,100) % fprintf('running the secant method...\n'); for i = 1:N fx2 = feval(f,x2); fx1 = feval(f,x1); dx = fx2*(x2 - x1)/(fx2 - fx1); x1 = x2; x2 = x2 - dx; fx2 = feval(f,x2); fprintf(' x = %e, dx = %e, f(x) = %e, \n', x2, dx, fx2); if (abs(fx2) < eps) | (abs(dx) < eps) x = x2; fail = 0; fprintf('succeeded after %d steps\n', i); return; end end fprintf('failed requirements after %d steps\n', N); x = x2; fail = 1;