how to calculate error using repeat simpsons rule in matlab

The repeated Simpson's rule can be used to approximate definite integrals with better accuracy. The error in using the repeated Simpson's rule can be calculated using the following formula:

main.m
err = (1/15) * abs(S2n - Sn)
29 chars
2 lines

where Sn is the previous approximation and S2n is the current approximation of the definite integral using the repeated Simpson's rule.

Here's an example code to demonstrate this:

main.m
% function to be integrated
f = @(x) x.*sin(x);

% limits of integration
a = 0;
b = pi;

% number of intervals
n = 4;

% repeated Simpson's rule
h = (b - a) / (2 * n);
x = a:h:b;
S = (h / 3) * (f(x(1)) + 4*f(x(2)) + f(x(3)));
for i = 2:n
    xi = a + (2*i - 2) * h;
    S = S + (h / 3) * (f(xi) + 4*f(xi + h) + f(xi + 2*h));
end
fprintf('Approximated value of integral using repeated Simpson''s rule: %.6f\n',S);

% error
h = (b - a) / (2 * (n+1));
x = a:h:b;
Sn = (h / 3) * (f(x(1)) + 4*f(x(2)) + f(x(3)));
for i = 2:n+1
    xi = a + (2*i - 2) * h;
    Sn = Sn + (h / 3) * (f(xi) + 4*f(xi + h) + f(xi + 2*h));
end
err = (1/15) * abs(S2n - Sn);
fprintf('Error in using repeated Simpson''s rule: %.6f\n',err);
709 chars
31 lines

In this example, the integral of x*sin(x) is approximated using the repeated Simpson's rule with n=4. The error is then calculated using the above formula.

related categories

gistlibby LogSnag