Problem with Less than or Equal to Operator <=

조회 수: 24 (최근 30일)
Shubham Patel
Shubham Patel 2018년 8월 13일
댓글: Shubham Patel 2018년 8월 13일
As shown in attached screenshot. I have two variables in my script.
  1. Distance_error- an local variable whose value at one point of time comes 0.001
  2. distance_resolution - a global variable which is constant as 1e-3.( which is of course 0.001)
Now if I compare these two varibles it doesnt give 'TRUE while if I put values a 0.001==1e-3, then the logical answer is TRUE.
How come this is possible?

채택된 답변

Stephen23
Stephen23 2018년 8월 13일
편집: Stephen23 2018년 8월 13일
"Problem with Less than or Equal to Operator"
Nope, there is no problem with the eq operator. All you have discovered is that two different binary floating point numbers are different, and that you should never test for equality of binary floating point numbers.
Always compare the difference of floating point numbers against a tolerance:
abs(A-B)<=tol
"How come this is possible?"
The value that you are trying to compare cannot be exactly represented using binary floating point numbers. What you see printed in the command window is the closest representation to 5 or 16 significant digits, depending on your current format setting. To see the "real" value download James Tursa's FEX submission:
Use James Tursa's num2strexact and you will see that none of those values really have the exact value 0.001. All you are looking at is a representation of those floating point numbers displayed in the command window, to the precision defined by your format setting. Just because you see 0.001 is displayed tells you nothing about the "real" floating point number's value.
Note that you can change how the value is displayed by changing the format.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:
  댓글 수: 1
Shubham Patel
Shubham Patel 2018년 8월 13일
Thank you very much. That is very helpful.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by