フィルターのクリア

Incorrect answer - Incorrect looping?

5 ビュー (過去 30 日間)
amateurintraining
amateurintraining 2017 年 11 月 22 日
回答済み: Walter Roberson 2017 年 11 月 22 日
I have a code:
function [ I, h ] = Simpson( f, a, b, tol )
n=2;
h=(b-a)/n;
x=h/3;
I=x*(f(a)+4*f((a+b)/2)+f(b));
Iold=I;
while abs((I-Iold)/Iold)>=tol
n=n+2;
h=(b-a)/n;
j=1:((n/2)-1);
term1=sum(f(a+2*j*h));
term1=2*term1;
i=1:(n/2);
term2=sum(f(a+(2*i-1)*h));
term2=term2*4;
x=h/3;
I=x*(f(a)+term1+term2+f(b));
if abs((I-Iold)/Iold)<tol
break
end
end
end
But when I test the code with this input:
[t_simp, h]=Simpson(@(x) cos(x),0,pi/2,10^-3)
I get
t_simp=
1.0023
h=
0.7854
When the answer should be
t_simp=
1.0000
h=
0.1963
From what I can tell, the code should loop 3 times before stopping. Right now, the code doesn't loop. What am I doing wrong?

採用された回答

Walter Roberson
Walter Roberson 2017 年 11 月 22 日
You do
Iold=I;
while abs((I-Iold)/Iold)>=tol
but when you execute that second line, you have just set Iold to I so I-Iold is going to be 0, which is not going to be greater than the tol

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by