Am beginner here, can anyone tell me What is wrong with the code with while loop?

The following code is a simplified version of my problem. Can anyone pointout why the loop is not terminating??
x=2;
y=2;
a=[x,y];
b=[10,10];
tf=isequal(a,b);
while tf==0
x=x+1;
y=y+1;
tf=isequal(a,b);
end
disp(a);

 Réponse acceptée

James Tursa
James Tursa le 31 Mai 2018
Modifié(e) : James Tursa le 31 Mai 2018
You never update the "a" vector inside the loop. It was built from the original values of x and y and never changes. To fix this:
while tf==0
x=x+1;
y=y+1;
a=[x,y]; % <-- add this line
tf=isequal(a,b);
end

3 commentaires

But the same code is not working with decimal increments
if true
% code
end
x=0.1;
y=0.1;
a=[x,y];
b=[0.2,0.2];
tf=isequal(a,b);
while tf==0
x=x+0.01;
y=y+0.01;
a=[x,y]
tf=isequal(a,b);
end
disp(a);
Because floating point arithmetic with fractional values is in general not exact. See this article:
"But the same code is not working with decimal increments"
Because the accumulated floating point error means that those values are NOT the same. See the answers to your later question:

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by