使用梯形法则近似积分

时间:2019-01-11 01:01:00

标签: matlab numeric

我正在尝试在Matlab中使用梯形方法以使相对误差为1%。这是我的代码:

a=0;b=2;

N=0;k=0;

it=0;is=0;

function y=g(x)

       d=1+x^3+x^4;

       y=x^2*d;

end

sumtn=0.5*(g(a)+g(b));sumt2n=sumtn;

while 1

        k=k+1;%Number of times I split the distance [a,b] in 
        equal parts

        N=2^k;%Number of parts that the distance is being 
        split for every iteration

        h=(b-a)/N;

        for i=1:N-1

                  xi=a+i*h;

                 xi2n=xi-h/2;%for 2*N parts

                 sumtn=sumtn+g(xi);

                 sumt2n=sumt2n+g(xi2n)+g(xi);

        end

       It2n=sumt2n*h/2;

       Itn=sumtn*h;

       Et=abs(It2n-Itn)/3;

       if Et/It2n<=0.01

                break;
      end
end

结果证明大约是预期值的两倍,所以我认为我缺少了一些东西。

0 个答案:

没有答案