Effacer les filtres
Effacer les filtres

Incorrect answer - Incorrect looping?

5 vues (au cours des 30 derniers jours)
amateurintraining
amateurintraining le 22 Nov 2017
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?

Réponse acceptée

Walter Roberson
Walter Roberson le 22 Nov 2017
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

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by