function [x,fail] = newton(f,df,x,eps,N) % % Applies Newton's method to the function f, with derivative in df, % starting at the point x. 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. % % Example : % >> [x,fail] = newton('sin','cos',pi/4,1e-8,10) % fprintf('running the method of Newton...\n'); fx = feval(f,x); for i = 1:N dx = fx/feval(df,x); x = x - dx; fx = feval(f,x); fprintf(' x = %e, dx = %e, f(x) = %e\n', x, dx, fx); if (abs(fx) < eps) | (abs(dx) < eps) fail = 0; fprintf('succeeded after %d steps\n', i); return; end end fprintf('failed requirements after %d steps\n', N); fail = 1;