Simpson's Rule
3 次查看(过去 30 天)
显示 更早的评论
I coded Simpson's Rule, but I'm not sure if it's right.
f = @(x) exp(-x.^2);
true = integral(f, 0, 1);
%simpson's rule
n = 128;
k= n/2;
a = 0; b = 1;
h = (b-a)/n;
x = a + h;
sum1 = (h/3)*(f(b)+ f(a));
sum1 = sum1 + (4*h/3)*f(x);
for j = 1:n-1
x1 = a+(2*j)*h;
x2 = a + (2*j+1)*h;
sum1 = sum1 + (2*h/3)*f(x1)+(4*h/3)*f(x2);
end
error1 = abs(true-sum1);
fprintf(' Simpsons %d : %0.8f \n', n, sum1);
fprintf('Simpsons Error: %0.8f \n', error1);
1 个评论
Geoff Hayes
2016-4-25
Chris - what makes you think that the algorithm has been coded incorrectly? Presumably you must have a set of test data that you will use to validate the above. What do you notice when you do so?
采纳的回答
Roger Stafford
2016-4-25
I think you made an error on the line
for j = 1:n-1
It should be
for j = 1:k-1
where k = n/2. As it stands now, the x2 reaches a value of a+(2*n-1)*h which is far beyond the range from 0 to 1.
0 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Numerical Integration and Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!