Incorrect answer - Incorrect looping?

2 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Walter Roberson
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

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by