p = 4; q = 7;
f = @(x) p./(q+x.^2);
a = 1.5;
n = 20; % number of intervals
h = a / n;
% Midpoint Rule:
I_m = 0;
for i=1:n
x = h*(i-0.5);
I_m = I_m + f(x);
end
I_m = I_m * h;
% Trapezoid Rule:
I_t = 0;
for i=1:n
x1 = h*(i-1);
x2 = h*i;
I_t = I_t + (f(x1) + f(x2))/2;
end
I_t = I_t * h;
% Simpson's 1/3 Rule:
I_s = 0;
for i=1:2:n
x1 = h*(i-1);
x2 = h*i;
x3 = h*(i+1);
I_s = I_s + (f(x1) + 4*f(x2) + f(x3))/3;
end
I_s = I_s * h;
fprintf('Midpoint value: %f\n', I_m);
fprintf('Trapezoid value: %f\n', I_t);
fprintf("Simpson's value: %f\n", I_s);
Comments
Leave a comment