Simpson Rule issue - Approximation worsens as n increases
Show older comments
I'm trying to create a function to estimate function area via the 1/3 Simpson Rule, but my results are odd. When I set the number of subintervals (n) to 2 (the lowest possible number for Simpson's Rule), it gets near the real answer. However as I increase n, my approximation gets worse (which is the opposite of what should happen). Can anyone help find what's wrong with my code? Thanks!
function sum=CompositeSimpson(f,a,b,n)
if (mod(n,2)~=0 )
disp('User! Give me an even number of subintervals!');
area=NaN; return;
end
sum=0;
h=(b-a)/n;
for i=1:(n/2)
a1=a+2*(i-1)*h;
b1=a+2*i*h;
sum=sum+((b1-a1)/2)/3*(f(a1)+4*f((b1-a1)/2)+f(b1));
end
end
My testing is using f=@(x) x^3-x^2+x, a=0, b=1. Here are the n values I used and their results:
2 - 0.4167
4 - 0.2812
6 - 0.2377
8 - 0.2148
10 - 0.2007
16 - 0.1785
20 - 0.1709
40 - 0.1552
Accepted Answer
More Answers (0)
Categories
Find more on Programming in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!