Primitive double value equal depends on magnitude?

后端 未结 3 1835
星月不相逢
星月不相逢 2020-12-29 17:05

I have to check to see whether two double values are equal including magnitude and precision. I encounter a weird scenario where primitive double equals check is not consist

相关标签:
3条回答
  • 2020-12-29 17:16

    Floating point numbers are approximations. They have a finite set of discrete values possible. When you create a floating point number by parsing a string, the closest possible floating point value is selected to represent it.

    The double closest to 15.999999999999999 is 15.999999999999998, not 16.0, so that comparison is unequal. But 17.0 is the closest double to 16.999999999999999, so they compare equal.

    0 讨论(0)
  • 2020-12-29 17:19

    dont use == when comparing double or float values.

    instead use Double.compare http://download.oracle.com/javase/6/docs/api/java/lang/Double.html

    and Float.compare for floats.

    0 讨论(0)
  • 2020-12-29 17:22

    What you're trying to do won't work for various boring and complicated reasons that you can read about here: http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

    Unless you're going to compare the bit-representation of the doubles (which may or may not be insightful), you will always need some sort of epsilon value, i.e. margin of error when dealing with floating-point representations of numbers. Something like:

    boolean doublesAreEqual(double d1, double d2)
    {
        double d = d1 / d2;
        return (Math.abs(d - 1.0) < 0.00001 /* epsilon */);
    }
    
    0 讨论(0)
提交回复
热议问题