在MATLAB中计算梯形规则的误差

时间:2014-06-19 11:01:44

标签: matlab numerical-methods

我正在尝试计算误差如何取决于梯形规则的步骤h。使用较小的h值时,错误应该会变小,但对我来说这不会发生。这是我的代码:

Iref是分别用Simpson方法和MATLAB函数quad计算和验证的参考值

for h = 0.01:0.1:1
    x = a:h:b;
    v = y(x);
    Itrap = (sum(v)-v(1)/2-v(end)/2)*h;
    Error = abs(Itrap-Iref)
end

我认为我使用h的方式有问题,因为梯形规则适用于已知的积分。如果有人可以帮我这个,我会很高兴,因为我无法理解为什么这些错误会像往常一样“跳来跳去”。

1 个答案:

答案 0 :(得分:0)

我想知道问题的一部分是否并非所有区间 - 对于每个步长h - 具有相同的ab只是因为{{1构造。请使用附加的x声明尝试以下操作:

fprintf

根据您的for h = 0.01:0.1:1 x = a:h:b; fprintf('a=%f b=%f\n',x(1),x(end)); v = y(x); Itrap = (sum(v)-v(1)/2-v(end)/2)*h; Error = abs(Itrap-Iref); end a(我选择了ba=0),所有b=5值都相同(如预期的那样),但{{{ 1}}从4.55到5.0不等。

我认为您总是希望为您选择的每个步长保持相同的时间间隔a,以便在每次迭代之间获得更好的比较。因此,不是迭代步长,而是迭代b[a,b]内等间隔子间隔的数量。

而不是

n

你可以做更像

的事情
[a,b]

当您评估上述代码时,您会注意到for h = 0.01:0.1:1 x = a:h:b; % iterate over each value of n, chosen so that the step size % is similar to what you had before for n = [501 46 24 17 13 10 9 8 7 6] % create an equally spaced vector of n numbers between a and b x = linspace(a,b,n); % get the step delta h = x(2)-x(1); v = y(x); Itrap = (sum(v)-v(1)/2-v(end)/2)*h; Error = abs(Itrap-Iref); fprintf('a=%f b=%f len=%d h=%f Error=%f\n',x(1),x(end),length(x),h,Error); end 对于每次迭代都是一致的,a大致是您之前选择的,b随着步长的增加,确实会增加。

尝试以上操作,看看会发生什么!