Code for a simpson's rule approximation of the integral of sin(x)/x

7 views (last 30 days)
I'm trying to do a simpson's approximation for the integral of sin(x)/x. This is what I have so far, for some reason the answer diverges as the number of sub-intervals (N) increases. Wondering if anyone can see what I'm doing wrong.
Function Hw5Num6(a,b,N)
dx = (b - a)/N;
% create our result variable
integral = 0;
% loop over the elements in the sum
for k=1:(N/2)
x = a + ((2*k)-1)*dx;
i = 4*(sin(x)/x);
if x==0
i = 4*1;
end
end
for k=1:((N-2)/2)
h = a + (2*k)*dx;
j = 2*(sin(h)/h);
if h==0
j = 2*1;
end
end
y = (sin(a))/a;
if a==0
y = 1;
end
z = (sin(b))/b;
integral = (dx/3)*(y + z + i + j);
return

Answers (1)

Geoff Hayes
Geoff Hayes on 14 Oct 2015
Evan - it isn't clear to me where you are performing your sums for each iteration of either loop. I see that you are setting an i and j to some value (note you should rename these two local variables as MATLAB also uses these same named variables to represent the imaginary number) but you are not summing up the result from each iteration.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!