If statement in for loop does not work

2 Ansichten (letzte 30 Tage)
Mohammed Radha Al Khazraji
Kommentiert: Jan am 9 Feb. 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

Antworten (2)

KALYAN ACHARJYA
KALYAN ACHARJYA am 9 Feb. 2021
Bearbeitet: KALYAN ACHARJYA am 9 Feb. 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 am 9 Feb. 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 Kommentar
Jan
Jan am 9 Feb. 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

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by