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

1 回表示 (過去 30 日間)
Evan H
Evan H 2015 年 10 月 14 日
回答済み: Geoff Hayes 2015 年 10 月 14 日
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

回答 (1 件)

Geoff Hayes
Geoff Hayes 2015 年 10 月 14 日
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.

カテゴリ

Help Center および File ExchangeProgramming についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by