Numerical Calculation Method-Numerical Integration Algorithm

Requirements:
1. Write a numerical integration function. The input is the upper and lower limits of integration, the number of segments, the integrand, and the integration method; the
method of compound integration is required. The function includes three compound integration methods: T, Simpson, and Cotes.
matlab code:
① main function

function y=integral(a,b,n,fun,flag)  
%a,b积分上下限,n分段段数,fun被积函数,flag积分方法: 1:T,2:S,3:C
h=(b-a)/n;
s0=0;
fa=subs(fun,a);
fb=subs(fun,b);
if flag==1
    for k = 1:n-1
        xk = a+k*h;
        s0 = s0+subs(fun,xk);
    end
    y = (h/2)*(fa+2*s0+fb);
end
if flag==2
    s1=subs(fun,a+0.5*h);
    for k = 1:n-1
        xk = a+k*h;
        s0 = subs(fun,xk)+s0;
        s1 = subs(fun,xk+(h/2))+s1;
    end
    y=(h/6)*(fa+2*s0+4*s1+fb);
end
if flag==3
   s1=0;
   s2=0;
   s3=0;
   for k = 1:n-1
        xk = a+k*h;
        s0 = s0+subs(fun,xk);
   end
   for k = 0:n-1
       xk = a+k*h;
       s1 = subs(fun,xk+(h/4))+s1;
       s2 = subs(fun,xk+(h/2))+s2;    
       s3 = subs(fun,xk+(3*h/4))+s3;
   end
   y=(h/90)*(7*fa+32*s1+12*s2+32*s3+14*s0+7*fb);
end

Guess you like

Origin blog.csdn.net/weixin_46837674/article/details/113032461