simpson's 3/8 rule in matlab

Simpson's 3/8 rule can be used for numerical integration. Here is a matlab code to do so:

main.m
function I = simpson38_rule(f, a, b)
% f : function to be integrated
% a, b : limits of integration

h = (b-a)/3;
I = h*(f(a) + 3*f(a+h) + 3*f(a+2*h) + f(b));
end
163 chars
8 lines

To use the above function for numerical integration, simply pass the function that needs to be integrated, and the limits of integration as inputs to the function. The output will be the numerical approximation of the integral.

For example, let's say we want to find the numerical approximation of the integral of sin(x) from 0 to pi/2. We can call the simpson38_rule function as follows:

main.m
>> I = simpson38_rule(@(x) sin(x), 0, pi/2)
I =

    0.999839171711558
71 chars
5 lines

Therefore, the numerical approximation of the integral of sin(x) from 0 to pi/2 using Simpson's 3/8 rule is approximately 0.9998.

gistlibby LogSnag