a181.m

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

M
42
字号
       %----------------------------------------------------------------
       % Example a1.8.1: Numerical Integration       
       %----------------------------------------------------------------

       % Initialize

       clc                 % clear command window 
       clear               % clear variables
       a = -1;             % lower limit
       b = 1;              % upper limit
       n = 100;            % number of panels
       randinit (500);     % select random sequence
       f = inline ('exp(-x.*x/2) ./ sqrt(2*pi)','x');

       % Simpson's method

       fprintf ('Example a1.8.1: Numerical Integration\n\n');
       y = simpson (a,b,n,f);
       fprintf ('Simpson: I(-1,1) = %.6f\n',y)

       % Direct method

       disp('Computing by direct method ...')
       c = 0;
       for k = 1 : 1000
          x = randg(1,1,0,1);
          if (x >= a) & (x <= b)
             c = c + 1;
          end
          if (k == 10) | (k == 100) | (k == 1000)
             fprintf ('direct, p = %5i  %.6f \n',k,c/k);
          end
       end

       % Trapezoid rule

       y = trapint(a,b,n,f);
       fprintf ('Trapezoid rule: I(-1,1) = %.6f\n',y)
       wait
       %----------------------------------------------------------------

⌨️ 快捷键说明

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