If statement in for loop does not work

2 visualizaciones (últimos 30 días)
Mohammed Radha Al Khazraji
Mohammed Radha Al Khazraji el 9 de Feb. de 2021
Comentada: Jan el 9 de Feb. de 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

Respuestas (2)

KALYAN ACHARJYA
KALYAN ACHARJYA el 9 de Feb. de 2021
Editada: KALYAN ACHARJYA el 9 de Feb. de 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 el 9 de Feb. de 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 comentario
Jan
Jan el 9 de Feb. de 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

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by