📄 secant.m
字号:
function [x, ithist, iflag] = secant( f, x, xo, tolf, tolx, maxit )%% function [x, ithist, iflag] = secant( f, x, xo, tolf, tolx, maxit )%% secant attempts to compute a root of f.%% Input parameters:% f name of a matlab function that evaluates % f and its derivative.% x initial iterate% xo additional point needed to start the second method% tolf stopping tolerance (optional. Default tolf = 1.e-7)% Secant method stops if |f(x)| < tolf% tolx stopping tolerance (optional. Default tolx = 1.e-7)% Secant method stops if |s| < tolx, % where s = -f(x_k)*(x_{k-1} - x_k)/f(x_{k-1}) - f(x_k))% is the secant 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 necessaryif( nargin <= 3 ) tolf = 1.e-7; tolx = 1.e-7; maxit = 100; endif( nargin <= 4 ) tolx = 1.e-7; maxit = 100; endif( nargin <= 5 ) maxit = 100; end it = 0;iflag = 0;[fx] = feval(f, x);[fo] = feval(f, xo);s = - fx*(xo-x)/(fo-fx);while( it < maxit & abs(s) > tolx & abs(fx) > tolf ) s = - fx*(xo-x)/(fo-fx); ithist(it+1,:) = [it, x, fx, s]; xo = x; fo = fx; x = x+s; it = it+1; [fx] = feval(f, x);end% check why the Secant method truncated and set iflagif( abs(fx) > tolf ) % Secant method truncated because the maximum number of iterations % was reached iflag = 1; returnelse % Secant method truncated because abs(fx) <= tolf % print info for last iteration ithist(it+1,:) = [it, x, fx, 0];end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -