Incorrect answer - Incorrect looping?

2 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by