Problem with Less than or Equal to Operator <=
조회 수: 22 (최근 30일)
이전 댓글 표시
As shown in attached screenshot. I have two variables in my script.
- Distance_error- an local variable whose value at one point of time comes 0.001
- 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?
댓글 수: 0
채택된 답변
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.
You need to learn about the limits of floating point numbers. Start by reading these:
This is worth reading as well:
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!