Integrate the functions below between the limits 0 and 1 by Simpson’s rule.
a) f(x) = sin(x)/(1+x^4)
b) f(x) = e^-x(1+x)^-5
c) f(x) = cos(x)e^-x^2
fun_a = @(x) sin(x) ./ (1 + x.^4);
fun_b = @(x) exp(-x)./(1+x).^5;
fun_c = @(x) cos(x) .* exp(-x.^2);
a = 0;
b = 1;
n = 1000;
h = (b-a) / n;
% Integral of sin(x) ./ (1 + x.^4)
i_a = fun_a(a) + fun_a(b);
for i=1:n-1
x = a + i*h;
if mod(i, 2) == 1
i_a = i_a + 4*fun_a(x);
else
i_a = i_a + 2*fun_a(x);
end
end
i_a = i_a * h/3;
disp(i_a)
% Integral of exp(-x)./(1+x).^5
i_b = fun_b(a) + fun_b(b);
for i=1:n-1
x = a + i*h;
if mod(i, 2) == 1
i_b = i_b + 4*fun_b(x);
else
i_b = i_b + 2*fun_b(x);
end
end
i_b = i_b * h/3;
disp(i_b)
% Integral of cos(x) .* exp(-x.^2)
i_c = fun_c(a) + fun_c(b);
for i=1:n-1
x = a + i*h;
if mod(i, 2) == 1
i_c = i_c + 4*fun_c(x);
else
i_c = i_c + 2*fun_c(x);
end
end
i_c = i_c * h/3;
disp(i_c)
Comments
Leave a comment