Primitive double value equal depends on magnitude?

后端 未结 3 1865
星月不相逢
星月不相逢 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: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 */);
    }
    

提交回复
热议问题