While comparing the equality of two floating numbers(a,b), we use abs(a – b) < tolerance. Could anyone let me know if there's anyway that this function may yield bad results or errors ?

9 次查看(过去 30 天)
For normal interger values, this test is the best to check the equality.I wish to know even if the tolerance set is proper but still the results are bad.

回答(2 个)

Jan
Jan 2016-2-13
Floating point numbers are stored with a limited precision according to the IEEE754 conventions (search for this term in the net for further details). Numbers are store in binary format internally and most decimal numbers do not have an exact binary representation. Therefor rounding error will occur and comparing numbers with a certain tolerance is required. The problem remains, that the value of this tolerance depends on the "physical" meaning of the numbers and there is no general concept to determine this.
A standard example:
0:0.1:1 == 0.3 % => all comparisons are FALSE!

Walter Roberson
Walter Roberson 2016-2-13
If one of the two values is NaN, then the negation of the test can be incorrect. (3 - NaN) < 1e-10 is false, so ~((3-NaN) < 1e-10) is true, which would normally would imply that (3-NaN) >= 1e-10 is true, but it is not.
When working with large numbers, one must be careful with the tolerance. For example, 10^18 as a floating point number cannot be distinguished from (10^18 + 100) as a floating point number.
  2 个评论
Suneel Kumar
Suneel Kumar 2016-2-14
编辑:Suneel Kumar 2016-2-14
Dear Walter,
Thank you so much for the answer. Could you please let me know why this below code is not working as you have mentioned in your answer? In addition to this, since this fails, which is the best way to check for the equality for the large numbers?
>> abs(10^20-(10^20+100))<=1
ans =
1
Walter Roberson
Walter Roberson 2016-2-14
Binary floating point effectively uses 53 bits of precision in representing numbers, so two numbers are only distinct if they differ by more than one part in 2^53. By the time you reach 10^20, the difference between adjacent representable numbers has reached 16384 so anything between 10^20 and (10^20 + (16384/2)) would compare equal, and 10^20+8193 rounding to the next representable number (because it would be more than half way through the range.)
As far as IEEE 754 binary floating point double precision representation is concerned, 10^20 and 10^20+100 are the same number.
10^20 also exceeds the limit that uint64 can store (which is about 1.8E19), so you cannot switch to uint64 for this situation.
If you need extended precision, you will need to switch to a software high precision toolbox. John D'Errico has added a couple to the File Exchange, or you could use the Symbolic Toolbox if you have access to that.

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by