function [x, ithist, iflag] = newt1d( f, x, tolf, tolx, maxit ) % % function [x, ithist, iflag] = newt1d( f, x, tolf, tolx, maxit ) % % newt1d attempts to compute a root of f. % % Input parameters: % f name of a matlab function that evaluates % f and its derivative. % x initial iterate % tolf stopping tolerance (optional. Default tolf = 1.e-7) % Newton's method stops if |f(x)| < tolf % tolx stopping tolerance (optional. Default tolx = 1.e-7) % Newton's method stops if |s| < tolx, % where s = -f(x)/f'(x) is the Newton step. % maxit maximum number of iterations (optional. Default maxit = 100) % % % Output parameters: % x approximation of the solution. % ithist array with the iteration history % The i-th row of ithist contains [it, x, fx, s] % ifag return flag % iflag = 0 |f(x)| <= tolf % iflag = 1 iteration terminated because maximum number of % iterations was reached. |f(x)| > tolf % % Matthias Heinkenschloss % Department of Computational and Applied Mathematics % Rice University % Jan 17, 2002 % % set tolerances if necessary if( nargin <= 3 ) tolf = 1.e-7; tolx = 1.e-7; maxit = 100; end if( nargin <= 4 ) tolx = 1.e-7; maxit = 100; end if( nargin <= 5 ) maxit = 100; end it = 0; iflag = 0; [fx,fpx] = feval(f, x); s = 2*tolx; while( it < maxit & abs(s) > tolx & abs(fx) > tolf ) s = - fx/fpx; ithist(it+1,:) = [it, x, fx, s]; x = x+s; it = it+1; [fx,fpx] = feval(f, x); end % check why the Newton's method truncated and set iflag if( abs(fx) > tolf ) % Newton's method truncated because the maximum number of iterations % was reached iflag = 1; return else % Newton's method truncated because abs(fx) <= tolf % print info for last iteration ithist(it+1,:) = [it, x, fx, 0]; end