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

后端 未结 21 1936
你的背包
你的背包 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:40

    In addition to previous answers, you should be aware that there are strange behaviours associated with -0.0f and +0.0f (they are == but not equals) and Float.NaN (it is equals but not ==) (hope I've got that right - argh, don't do it!).

    Edit: Let's check!

    import static java.lang.Float.NaN;
    public class Fl {
        public static void main(String[] args) {
            System.err.println(          -0.0f   ==              0.0f);   // true
            System.err.println(new Float(-0.0f).equals(new Float(0.0f))); // false
            System.err.println(            NaN   ==               NaN);   // false
            System.err.println(new Float(  NaN).equals(new Float( NaN))); // true
        }
    } 
    

    Welcome to IEEE/754.

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

    One way to reduce rounding error is to use double rather than float. This won't make the problem go away, but it does reduce the amount of error in your program and float is almost never the best choice. IMHO.

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

    Floating point values can be off by a little bit, so they may not report as exactly equal. For example, setting a float to "6.1" and then printing it out again, you may get a reported value of something like "6.099999904632568359375". This is fundamental to the way floats work; therefore, you don't want to compare them using equality, but rather comparison within a range, that is, if the diff of the float to the number you want to compare it to is less than a certain absolute value.

    This article on the Register gives a good overview of why this is the case; useful and interesting reading.

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