If statement in for loop does not work

조회 수: 1 (최근 30일)
Mohammed Radha Al Khazraji
Mohammed Radha Al Khazraji 2021년 2월 9일
댓글: Jan 2021년 2월 9일
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

답변 (2개)

KALYAN ACHARJYA
KALYAN ACHARJYA 2021년 2월 9일
편집: KALYAN ACHARJYA 2021년 2월 9일
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 2021년 2월 9일
%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
Jan
Jan 2021년 2월 9일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by