While loop does not iterate
Afficher commentaires plus anciens
Hello,
I am trying to write the bisection method manually but having problems with the while loop. I am calculating the error in the loop and i want it to go on until the error reaches 0.05 %.
But the code wont work. It only does the first iteration and the ans =1 , logical appears on the command window and it freezes.
I would appreciate any help.
Here is what i did;
x1=1;
x2=2;
bb=0;
err = 2;
%bisection
while ne(err,0.05)
y1 = sin(exp(-x1))-cos(x1);
y2 = sin(exp(-x2))-cos(x2);
carpim = y1*y2;
if le(carpim,0)
xm = (x1+x2)/2;
ym = sin(exp(-xm))-cos(xm);
cc = y1*ym;
cc2 = y2*ym;
if le(cc2,0)
bb = y2;
y2 = ym;
err = (y2-bb)*100/y2;
else
le(cc,0)
bb=y1;
y1 = ym;
err = (y1-bb)*100/y1;
end
end
end
2 commentaires
dpb
le 10 Mar 2019
while ne(err,0.05)
will run until the value of err is identically equal to 0.05 which probably will never happen. Hence, you've written an infinite loop for all cases other than a fluke, rare event. What you probably intended was something like
while err>0.05
instead altho I've not tried to debug your code, that's likely a good start.
dpb
le 10 Mar 2019
Intended to write
while abs(err)>0.05
Réponses (1)
KALYAN ACHARJYA
le 10 Mar 2019
Modifié(e) : KALYAN ACHARJYA
le 10 Mar 2019
No the iteration going on, may be infinite
@dpb already suggested you to use
while err>0.05
end
and second approach use
err=abs() % absolute error
Please carefully check the data and expression to validate the data, so that the error reaches the value less than 0.05 and iteration number not goes large or infinite.
As the error value is not changing in large iterations also (check the expression)
err =
220.0063
err =
220.0063
Therefore while loop true always and code running infinite.
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!