If statement in for loop does not work

2 vues (au cours des 30 derniers jours)
Mohammed Radha Al Khazraji
Commenté : Jan le 9 Fév 2021
I am trying to model a particle bouncing around in a box. The size of the box is 0<=x<=1 and 0<=y<=1. so given an initial position and velocity the particle will move until it hits a wall and then it bounces. I have an idea of how this should work but as I was working through the project I hit this problem. This is a simplified version of the code that is causing the problem. the value of x is 1 at some point in the iteration but the if statement doesnt recognmize it.
x = 0.5;
for i=1:6
x = x+0.1
if x == 1
disp('yes')
end
end

Réponses (2)

KALYAN ACHARJYA
KALYAN ACHARJYA le 9 Fév 2021
Modifié(e) : KALYAN ACHARJYA le 9 Fév 2021
It's because floating point numbers representation (Exactly). Hence If you're trying to do logical comparision (==) with floating-point numbers, be careful.
Please refer the following
More:
But if you are insisted to way out, you may consider difference between the numbers as allowable tolerance (error) and use > or < logical comparision in the "if statement".
Hope it Helps!

randerss simil
randerss simil le 9 Fév 2021
%if true
x = 0.5;
for i=1:6
x = (x)+0.1
if strcmp(num2str(x),'1')
disp('yes')
end
end
Try the above
  1 commentaire
Jan
Jan le 9 Fév 2021
Letting strcmp perform a rounding is a very indirect and instable way. The actual poblem of floating point number is not addressed here. Using a limit for the numeric comparison is better: if abs(x - 1) < 10 * eps

Connectez-vous pour commenter.

Catégories

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

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by