If statement not executing

I'm running into a really weird problem . In my Matlab code, the statement if (time == 0.0992) does not execute, but when I write it in the form if (time== 0.0016*62), it does execute.
Now, since 0.0016*62 is equal to 0.0992, I don't see why the first statement is any different from the second.
NOTE : 'time' is a variable who's value is used as a operating condition for the if statement

댓글 수: 1

Jan
Jan 2012년 3월 4일
Welcome to the world of floating point numbers.

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

 채택된 답변

Wayne King
Wayne King 2012년 3월 4일

1 개 추천

Hi, They aren't really equal:
a = 0.0016*62;
b = 0.0992;
isequal(a,b)
This is a well known problem discussed in this forum frequently with the representation of floating-point numbers.
You should use some tolerance statement like
time = 0.0016*62;
if(abs(time-0.0992)< eps)
disp('True');
else
disp('False');
end
Or something similar, trying to insist on equality with floating-point numbers is going to cause you a lot of problems.

카테고리

도움말 센터File Exchange에서 Introduction to Installation and Licensing에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by