Numerical Integration with Trapezoidal and Simpson's Rule

17 views (last 30 days)
I am doing numerical integration using the trapezoidal rule, and the simpson's 1/3, and simpson's 3/8 rule and checking the error against the exact. I am not getting the correct output for the trap and simpson equations, and cannot figure out what I am doing wrong.
if true
% function [I,eps_t]=Integration_Exercise(part)
%%Input
% part: string 'a' through 'f' for type of integration (scalar)
% 'a' analytically
% 'b' trapezoidal rule, n = 4
% 'c' trapezoidal rule, n = 8
% 'd' Simpson 1/3, n = 4
% 'e' Simpson 3/8, n = 3
%
%%Output
% I: result of the integration (scalar)
% eps_t: true absolute percent relative error (scalar)
%%Write your code here
F = @(x) (8+4*cos(x));
a = 0;
b = pi/2;
Exact = integral(F,0,pi/2);
function f = trapInt(f,l,u,n) % Inputs constraints for trapizoidally calc
h = (u-l)/(n-1);
x = linspace(l,u,n);
y = zeros(n,1);
for i = 1:n
y(i) = f(x(i));
end
f = 1/2 * (y(1) + y(end));
for i = 2:n-1
f = f+y(i);
end
f = h*f;
end
function f=simpson13(f,l,u,n) % Simpson Rule
h = (u-l)/(2*n);
x = linspace(l,u,2*n+1);
y = zeros(2*n+1,1);
for i = 1:2*n+1
y(i) = f(x(i));
end
f=0;
for i = 1:n
f = f + (y(2*i-1) + 4 * y(2*i)+ y(2*i+1));
end
f = h * f/3;
end
function f=simpson38(f,l,u,n) % Simpson Rule
h = (u-l) / (3*n);
x = linspace(l,u,(3*n+1));
y = zeros(3*n,1);
for i = 1:3*n+1
y(i) = f(x(i));
end
f = 0;
for i = 1:n
f = f + (y(3*i-2) + 3*y( 3*i-1) + 3*y(3*i) + y(3*i+1));
end
f = 3 * h * f/8;
end
if part == 'a'
I = Exact;
eps_t = 0;
end
if part == 'b'
I = trapInt(F,a,b,4);
eps_t = abs (Exact-I) / Exact*100;
end
if part == 'c'
I = trapInt(F,a,b,8);
eps_t = abs (Exact-I)/Exact*100;
end
if part == 'd'
I = simpson13(F,a,b,4);
eps_t = abs (Exact-I)/Exact*100;
end
if part == 'e'
I = simpson38(F,a,b,3);
eps_t = abs (Exact-I)/Exact*100;
end
end % End function
end
  1 Comment
Torsten
Torsten on 8 Dec 2017
Even if the homework problem tells you which "n" to use , I suggest that you check your code by using higher values for n. The error between exact and approximate solution should become arbitrarily small.
I checked your code superficially and at least in the trapezoidal rule, I could not find a mistake.
But I wonder why you use h=(u-l)/(2*n) and h=(u-l)/(3*n) within the other rules. Usually, given n, n+1 is the number of evaluation points within the interval and not 2*n+1 or 3*n+1.
Furthermore, in simpson38, you should initialize y=zeros(3*n+1), not y(3*n) (if you want to stick to 3*n instead of n).
Best wishes
Torsten.

Sign in to comment.

Answers (0)

Categories

Find more on Numerical Integration and Differential Equations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!