How to compare that sequence of doubles are all “approximately equal” in Java?

前端 未结 7 2129
感动是毒
感动是毒 2021-02-07 02:22

I have a method in java that returns a double number and I want to compare every double number that is returned every time I call the method(say 5 times), so that I can conclude

7条回答
  •  礼貌的吻别
    2021-02-07 02:49

    It depends on what you mean by similar. If you want to compare two numbers within an absolute error e.g. 1e-6 you can use epsilon. If you want to compare two double regardless of scale. e.g. 1.1e-20 and 1.3e-20 are not similar but 1.1e20 and 1.1e20+1e5 are you can compare the raw value.

    public static void main(String... args) throws IOException {
        test(1.1e-20, 1.3e-20);
        test(1.1e20, 1.1e20 + 1e5);
    }
    
    private static void test(double a, double b) {
        System.out.println(a + " and " + b + ", similar= " + similarUnscaled(a, b, 10));
    }
    
    public static boolean similarUnscaled(double a, double b, long representationDifference) {
        long a2 = Double.doubleToRawLongBits(a);
        long b2 = Double.doubleToRawLongBits(b);
        // avoid overflow in a2 - b2
        return ((a2 >= 0) == (b2 >= 0)) &&
                Math.abs(a2 - b2) <= representationDifference;
    }
    

    prints

    1.1E-20 and 1.3E-20, similar= false
    1.1E20 and 1.100000000000001E20, similar= true
    

提交回复
热议问题