标签:com highlight pre mat n+1 计算方法 sim tla ==
此段代码是基于辛普森公式的积分计算方法
1.代码
%%复合辛普森求积公式 %%Y是数值(attribute=0)或具体表达式(attribute=1),interval是求积区间,n是精度(如果是数值,则为数值长度-1) function CSQF = Compound_Simpson_quadrature_formula(Y,interval,n,attribute) a = interval(1);b = interval(2); h = (b-a)/n;lambda = 0.5; for i = 1:n+1 X(i) = a+h*(i-1); end if attribute == 0 for i = 1:n r = rand(1); Y_ave(i) = r*lambda*Y(i)+(1-r*lambda)*Y(i+1); end sum1 = 0; sum2 = 0; for i = 1:n sum1 = sum1+Y_ave(i); end for i = 2:n sum2 = sum2+Y(i); end CSQF = vpa(h*(Y(1)+Y(n+1)+4*sum1+2*sum2)/6,8); elseif attribute ==1 F = subs(Y,X); for i = 1:n r = rand(1); F_ave(i) = r*lambda*F(i)+(1-r*lambda)*F(i+1); end sum1 = 0; sum2 = 0; for i = 1:n sum1 = sum1+F_ave(i); end for i = 2:n sum2 = sum2+F(i); end CSQF = vpa(h*(F(1)+F(n+1)+4*sum1+2*sum2)/6,8); end end
2.例子
syms x; Y = exp(x)*sin(x)+log(x+1); interval=[0 pi]; attribute = 1; n = 1000; Compound_Simpson_quadrature_formula(Y,interval,n,attribute) vpa(int(Y,x,interval),8)
3.结果
ans = 14.815334 ans = 14.81429
通过结果看出,辛普森求积公式的精度并不是很高,同复合梯形公式一样,取决于求积精度和积分表达式复杂程度
标签:com highlight pre mat n+1 计算方法 sim tla ==
原文地址:https://www.cnblogs.com/guliangt/p/12243064.html