1
function simps(a, b, n) %simps(a, b, n) approximates the integral of a function f(x) in the %interval [a;b] by the composite simpson rule %n is the number of subintervals %the user needs to specify the function f(x) at the bottom %Author: Alain G. Kapitho %Date : Jan 2006 h = (b-a)/n; sum_even = 0; for i = 1:n/2-1 x(i) = a + 2*i*h; sum_even = sum_even + f(x(i)); end sum_odd = 0; for i = 1:n/2 x(i) = a + (2*i-1)*h; sum_odd = sum_odd + f(x(i)); end integral = h*(f(a)+ 2*sum_even + 4*sum_odd +f(b))/3 %this needs to be changed accordingly with the specific problem you have at %hand, before proceeding to the command line function y = f(x) y = exp(x);

Function Simps

Embed Size (px)

DESCRIPTION

matlab

Citation preview

function simps(a, b, n)

function simps(a, b, n)

%simps(a, b, n) approximates the integral of a function f(x) in the

%interval [a;b] by the composite simpson rule

%n is the number of subintervals

%the user needs to specify the function f(x) at the bottom

%Author: Alain G. Kapitho

%Date : Jan 2006

h = (b-a)/n;

sum_even = 0;

for i = 1:n/2-1

x(i) = a + 2*i*h;

sum_even = sum_even + f(x(i));

end

sum_odd = 0;

for i = 1:n/2

x(i) = a + (2*i-1)*h;

sum_odd = sum_odd + f(x(i));

end

integral = h*(f(a)+ 2*sum_even + 4*sum_odd +f(b))/3

%this needs to be changed accordingly with the specific problem you have at

%hand, before proceeding to the command line

function y = f(x)

y = exp(x);