This is from my final, so code is way long than it should be :D
function compSimpson(f,a,b)
c =quadgk(f,a,b);
int_approx=zeros;
hMatrix=zeros;
error=zeros;
s=zeros;
m=1:10;
disp('integal area of f =')
disp(c)
disp('-------------------------------------------')
disp([' m h ', ' approx', ' error slope'])
disp('-------------------------------------------')
for n=1:1:10
h = (b-a)/n;
sum = 0;
sumtwo = 0;
sumthree= 0;
for k = a+h: 3*h:b-h
sum = sum + f(k);
end
for j= a+2*h:3*h:b-h
sumtwo = sumtwo + f(j);
end
for w= a+3*h: 3*h: b-h
sumthree=sumthree+f(w);
end
int_approx(n, 1) = (3*h/8)*(f(a)+f(b)+3*sum+3*sumtwo+ 2*sumthree);
hMatrix(n,1)= h;
error(n,1)=abs((3*h/8)*(f(a)+f(b)+3*sum+3*sumtwo+ 2*sumthree)-c);
end
ssum=0;
for n= 2:10
s(1,1)=0;
s(n,1)= log(error(n,1)/ error(n-1,1) ) /log(hMatrix(n,1)/hMatrix(n-1,1));
ssum= ssum+ s(n,1);
end
averageOfSlope= log(error(9,1)/error(1,1))/log(hMatrix(9,1)/hMatrix(1,1)) ;
figure
loglog(hMatrix, error,'>-')
xlabel('h')
ylabel('error')
T=evalc('f');
legend(T,'Location','northwest')
legend('boxoff')
m =m';
disp([m,hMatrix, int_approx, error, s])
disp('-------------------------------------------')
disp(' ')
disp(['the average of the slope goes to ',num2str(averageOfSlope)])
end

EDU>> f=@(x) sin(pi*x)
f =
EDU>> compSimpson(f,0,1) integal area of f = 0.6366
----------------------------------------------------------
m h approx error slope
----------------------------------------------------------
1.0000 1.0000 0.0000 0.6366 0
2.0000 0.5000 0.5625 0.0741 3.1025
3.0000 0.3333 0.6495 0.0129 4.3124
4.0000 0.2500 0.6127 0.0239 -2.1457
5.0000 0.2000 0.6211 0.0155 1.9518
6.0000 0.1667 0.6373 0.0006 17.4724
7.0000 0.1429 0.6287 0.0080 -16.3520
8.0000 0.1250 0.6305 0.0061 1.9866
9.0000 0.1111 0.6367 0.0001 33.2404
10.0000 0.1000 0.6327 0.0039 -32.9430
-------------------------------------------
the average of the slope goes to 3.897
comment:
for this problem, we can conclude that simpson’s 3/8 rule is accurate if m(number of panels) is multiple of 3. Moreover, the order of the error formula for composite Simpson’s 3/8 rule is about 4
1 Comment
Direct link to this comment
https://de.mathworks.com/matlabcentral/answers/107240-why-is-my-simpson-s-3-8-code-not-producing-the-correct-values#comment_257394
Direct link to this comment
https://de.mathworks.com/matlabcentral/answers/107240-why-is-my-simpson-s-3-8-code-not-producing-the-correct-values#comment_257394
Sign in to comment.