MATLAB Answers

Problem with Less than or Equal to Operator <=

30 ビュー (過去 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?

採用された回答

Stephen Cobeldick
Stephen Cobeldick 2018 年 8 月 13 日
編集済み: Stephen Cobeldick 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 件)

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by