Why does this if statement fail?

조회 수: 1 (최근 30일)
Renat Yakupov
Renat Yakupov 2020년 9월 7일
댓글: Stephen23 2020년 9월 7일
I have noticed this strange behavior and I just can't figure why this is happening.
I have a script looping through a certain parameter and then saving some output results for certain values of that parameter. The relevant part of the script is:
for Thr=0.4:0.1:0.7
disp(Thr);
if Thr==0.5
disp('but I am here?');
end
if Thr==0.6
disp('am i here?');
end
end
>>
0.4000
0.5000
but I am here?
0.6000
0.7000
For some reason, it the if statement doesnt recognize Thr value of 0.6. If I use a step of 0.01, same happens for Thr values of 0.59, 0.58 and 0.57. I didnt test much further than that.
What is happening here?
  댓글 수: 2
Renat Yakupov
Renat Yakupov 2020년 9월 7일
I had no idea. That variable is different from 0.6 by 1e-16. That makes sense now. Thanks for the links!

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

채택된 답변

KSSV
KSSV 2020년 9월 7일
편집: KSSV 2020년 9월 7일
for Thr=0.4:0.1:0.7
disp(Thr);
if abs(Thr-0.5)<10^-3
disp('but I am here?');
end
if abs(Thr-0.6)<10^-3
disp('am i here?');
end
end
Read about comparing floating point numbers. It seems you are checking some options, you need not to do this. Please read abour debugging MATLAB files.
  댓글 수: 2
Renat Yakupov
Renat Yakupov 2020년 9월 7일
Thanks for the tip. In simpler cases like this, rounding to the first decimal also does the trick, but it certainly has to be more flexible for other cases.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by