What's wrong with using == to compare floats in Java?

后端 未结 21 1938
你的背包
你的背包 2020-11-22 01:00

According to this java.sun page == is the equality comparison operator for floating point numbers in Java.

However, when I type this code:



        
相关标签:
21条回答
  • 2020-11-22 01:32

    As mentioned in other answers, doubles can have small deviations. And you could write your own method to compare them using an "acceptable" deviation. However ...

    There is an apache class for comparing doubles: org.apache.commons.math3.util.Precision

    It contains some interesting constants: SAFE_MIN and EPSILON, which are the maximum possible deviations of simple arithmetic operations.

    It also provides the necessary methods to compare, equal or round doubles. (using ulps or absolute deviation)

    0 讨论(0)
  • 2020-11-22 01:33

    You can use Float.floatToIntBits().

    Float.floatToIntBits(sectionID) == Float.floatToIntBits(currentSectionID)
    
    0 讨论(0)
  • 2020-11-22 01:35

    Here is a very long (but hopefully useful) discussion about this and many other floating point issues you may encounter: What Every Computer Scientist Should Know About Floating-Point Arithmetic

    0 讨论(0)
  • 2020-11-22 01:37

    As of today, the quick & easy way to do it is:

    if (Float.compare(sectionID, currentSectionID) == 0) {...}
    

    However, the docs do not clearly specify the value of the margin difference (an epsilon from @Victor 's answer) that is always present in calculations on floats, but it should be something reasonable as it is a part of the standard language library.

    Yet if a higher or customized precision is needed, then

    float epsilon = Float.MIN_NORMAL;  
    if(Math.abs(sectionID - currentSectionID) < epsilon){...}
    

    is another solution option.

    0 讨论(0)
  • 2020-11-22 01:37

    Foating point values are not reliable, due to roundoff error.

    As such they should probably not be used for as key values, such as sectionID. Use integers instead, or long if int doesn't contain enough possible values.

    0 讨论(0)
  • 2020-11-22 01:37

    Two different calculations which produce equal real numbers do not necessarily produce equal floating point numbers. People who use == to compare the results of calculations usually end up being surprised by this, so the warning helps flag what might otherwise be a subtle and difficult to reproduce bug.

    0 讨论(0)
提交回复
热议问题