midpoint.m

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

M
39
字号
function y = midpoint (a,b,n,f)
%-----------------------------------------------------------------------
% Usage:       y = midpoint (a,b,n,f);
%
% Description: Use the midpoint rule to numerically integrate the
%              function f(x) over the interval [a,b] using n panels.
%
% Inputs:      a = lower limit of integration
%              b = upper limit of integration
%              n = number of panels (n >= 1)
%              f = string containing name of user-supplied function 
%                  to be integrated. The form of f is:
%
%                  function y = f(x)
%
%                  When f is called it must return the value f(x).
%
% Outputs:     y = estimate of integral
%
% Note:        The truncation error is proportional to pow(n,-2). 
%              The midpont rule is an open integration formula that
%              does not requres the value of f(x) at the end points,
%              a and b. 
%-----------------------------------------------------------------------

% Initialize

   n = args (n,1,n,4,'midpoint');
   h = (b - a)/n;

% Compute integral

   y = 0;
   for i = 1 : n
      y = y + feval(f,a+(2*i-1)*h/2);
   end
   y = h*y;
%-----------------------------------------------------------------------

⌨️ 快捷键说明

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