Problem with Less than or Equal to Operator <=

22 次查看(过去 30 天)
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:

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by