In: Advanced Math
17. Integrate the function sin(x) from 0 to π using Riemann and Simpson integration methods with N subintervals, where N increases by factors of 2 from 2 to 256 (i.e. N = 2, N = 4, etc.). Plot the relative error ∆I/I = [| estimated value - true value |/(true value)], assuming the
highest value of N gives the ‘true’ value. Which method converges the fastest?
17.Matlab code
x1 = 0;
x2 = pi;
f=@(x) sin(x);
%N=128;
for N=2:2:256
dx=(x2-x1)/N;
summe=0.0;
for i=1:N
summe=summe+f(x1+dx*(i-1));
end
summe=summe*dx
z=integral(f,x1,x2);%true value
rel_error=abs(summe-z)/z
plot(N,rel_error,'*')
pause(0.5)
end
Output
summe =
2.0000
rel_error =
1.2550e-05
Simpson integration
function I = simpsons(f,a,b,n)
f=@(x)sin(x);
a=0;b=pi;
for n=2:2:256
h=(b-a)/n; xi=a:h:b;
I=
h/3*(f(xi(1))+2*sum(f(xi(3:2:end-2)))+4*sum(f(xi(2:2:end)))+f(xi(end)))
Z=integral(f,a,b);%true value
relative_error=abs(Z-I)/Z
plot(n,relative_error,'*')
pause(0.5)
end
Output
relative_error =
1.2600e-10
ans =
2.0000
clearly from the output we see that Simpsons Integration converges faster than the riemann integration methods with N subintervals.