newton.m

来自「sareli<matlab科学计算>配套程序」· M 代码 · 共 33 行

M
33
字号
function [zero,res,niter]=newton(f,df,x0,tol,nmax,varargin)%NEWTON Find function zeros.%   ZERO=NEWTON(FUN,DFUN,X0,TOL,NMAX) tries to find the zero ZERO of the %   continuous and differentiable function FUN nearest to X0 using the Newton %   method. FUN and its derivative DFUN accept real scalar input x and returns %   a real scalar value. If the search fails an errore message is displayed.%   FUN and DFUN can also be inline objects.%%   [ZERO,RES,NITER]= NEWTON(FUN,...) returns the value of the residual in ZERO%   and the iteration number at which ZERO was computed.x = x0; fx = feval(f,x,varargin{:}); dfx = feval(df,x,varargin{:});niter = 0; diff = tol+1;while diff >= tol & niter <= nmax   niter = niter + 1;   diff = - fx/dfx;   x = x + diff;        diff = abs(diff);   fx = feval(f,x,varargin{:});           dfx = feval(df,x,varargin{:});endif niter > nmax    fprintf(['newton stopped without converging to the desired tolerance',...    'because the maximum number of iterations was reached\n']);    varargin{:}endzero = x;res = fx;return

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?