If statement in for loop does not work

1 view (last 30 days)
Mohammed Radha Al Khazraji
Commented: Jan on 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

Answers (2)

KALYAN ACHARJYA
KALYAN ACHARJYA on 9 Feb 2021
Edited: KALYAN ACHARJYA on 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 on 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 Comment
Jan
Jan on 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

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!