测试两个两倍的近似相等

时间:2019-11-18 17:49:39

标签: math double

给出这两个double值

double d1 = 1.0E-24;
double d2 = 1.0000000000000029E-24;  

以及以下功能

public static boolean isEqual(double d0, double d1, double epsilon) {
    return d0 == d1 ? true : Math.abs(d0 - d1) < epsilon;
}

如何计算最小的epsilon(最小的两倍距离),以便项Math.abs(d0 - d1) < epsilon的计算结果为true?

已针对评论进行了编辑:

我知道方法Double.doubleToRawLongBits,但仍需要澄清一些我需要比较的位。 因此,两个双精度值的二进制表示形式都是

d1: 0 11101011110 0011010101111100001010011001101010001000111010100111

d2: 0 11101011110 0011010101111100001010011001101010001000111010110111

我是否只需要比较像这样的尾数位?

isEqual(getMantissaLongBits(d1), getMantissaLongBits(d2), epsilon(getMantissaLongBits(d1), getMantissaLongBits(d2),49))? 

private static long getMantissaLongBits(double x) {
    return Double.doubleToRawLongBits(x) & 0x000fffffffffffffL;
}

public static double epsilon(final double one, final double other, final int bits) {
    return Math.max(Math.scalb(Math.max(Math.abs(one), Math.abs(other)), -bits),
            Math.scalb(Double.MIN_NORMAL, 52 - bits));
}

0 个答案:

没有答案
相关问题