Incorrect answer - Incorrect looping?
2 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
amateurintraining
il 22 Nov 2017
Risposto: Walter Roberson
il 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?
0 Commenti
Risposta accettata
Walter Roberson
il 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
0 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!