secant.m

来自「matlab算法集 matlab算法集」· M 代码 · 共 70 行

M
70
字号
function [x,k] = secant (x0,x1,tol,m,f,dm)
%----------------------------------------------------------------
% Usage:       [x,k] = secant (x0,x1,tol,m,f,dm)
%
% Description: Apply the secant method to find a root of:
%
%                   f(x) = 0
%
% Inputs:       x0  = first initial guess
%               x1  = second initial guess (x1 <> x0)
%               tol = error tolerance used to terminate search 
%                     (tol >= 0)
%               m   = maximum number of iterations (m >= 1)
%               f   = string containing name of user-supplied
%                     function.  The function f is of the form:
%
%                     function y = f(x)
%
%               dm  = optional display mode.  If present, 
%                     intermediate results are displayed.
%
% Outputs:      x = Estimated root of f(x) = 0 
%               k = number of iterations peroformed. If k < m,
%                   then the following convergence criterion
%                   was satisfied:
%
%                   |f(x)| < eps
%----------------------------------------------------------------

% Initialize 

   if abs(x1-x0) < eps
      fprintf ('Secant requires that x1 <> x0.\n');
      return
   end
   tol = args (tol,0,tol,3,'secant');
   m   = args (m,1,m,4,'secant');
   display = nargin > 5;

   f0 = feval(f,x0);
   f1 = feval(f,x1);
   if display
      fprintf ('\n 0 & %10.7f & %10.7f \\\\',x0,abs(f0)); 
      fprintf ('\n 1 & %10.7f & %10.7f \\\\',x1,abs(f1)); 
      fprintf ('\n \\hline');
   end

% Find root 

   k = 1;
   y = eps + 1;
   while (y > eps) & (k <= m);
      x2 = x1 - (x1-x0)*f1/(f1-f0);
      x0 = x1;
      f0 = f1;
      x1 = x2;
      f1 = feval(f,x2);
      y = abs(f1);
      if display
         fprintf ('\n%2g & %10.7f & %10.7f \\\\',k+1,x1,y); 
      end
      k = k + 1;
   end

% Finalize 

   x = x2;   
   k = k - 1;

⌨️ 快捷键说明

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