如何在Java中将浮点数的有效位数截断为任意精度?

时间:2018-02-11 01:42:00

标签: java floating-point precision ieee-754

我想将一些人工精确度损失引入两个数字进行比较,以平滑次要的舍入误差,这样我就不必在涉及Math.abs(x - y) < eps的每个比较中使用x惯用语和y

基本上,我想要的行为类似于将double向下转换为float,然后将其向上转换回double,除非我想保留非常大而小的指数,我希望能够控制保留的有效位数。

给出以下函数,该函数生成64位IEEE 754数字的有效数字的二进制表示:

public static String significand(double d) {
    int SIGN_WIDTH = 1;
    int EXP_WIDTH = 11;
    int SIGNIFICAND_WIDTH = 53;
    String s = String.format("%64s", Long.toBinaryString(Double.doubleToRawLongBits(d))).replace(' ', '0');
    return s.substring(0 + SIGN_WIDTH, 0 + SIGN_WIDTH + EXP_WIDTH);
}

我想要一个函数reducePrecision(double x, int bits),它会降低double的有效位数的精度,使得:{/ p>

significand(reducePrecision(x, bits)).substring(bits).equals(String.format("%0" + (52 - bits) + "d", 0))

换句话说,bits之后的每个位 - reducePrecision(x, bits)的有效位中的最高有效位应为0,而bits - 有效位中的最高有效位reducePrecision(x, bits) 1}}应合理地近似bits - x的有效位中最重要的位。

1 个答案:

答案 0 :(得分:0)

假设x是您希望降低精度的数字,bits是您希望保留的有效位数。

bits足够大且x的数量级足够接近0时,x * (1L << (bits - Math.getExponent(x)))将缩放x以便需要的位数remove将出现在小数分量中(在小数点之后),而将保留的位将出现在整数分量中(在小数点之前)。然后,您可以对此进行舍入以删除小数分量,然后将舍入后的数字除以(1L << (bits - Math.getExponent(x))),以恢复x的数量级,即:

public static double reducePrecision(double x, int bits) {
    int exponent = bits - Math.getExponent(x);
    return Math.round(x * (1L << exponent)) / (1L << exponent);
}

但是,(1L << exponent)会在Math.getExponent(x) > bits || Math.getExponent(x) < bits - 62时崩溃。解决方案是使用Math.pow(2, exponent)(或来自this answer的快速pow2(exponent)实现)来计算2的分数或非常大的幂,即:

public static double reducePrecision(double x, int bits) {
    int exponent = bits - Math.getExponent(x);
    return Math.round(x * Math.pow(2, exponent)) * Math.pow(2, -exponent);
}

然而,当Math.pow(2, exponent)接近-1074或+1023时,exponent会崩溃。解决方案是使用Math.scalb(x, exponent),因此不必明确计算2的幂,即:

public static double reducePrecision(double x, int bits) {
    int exponent = bits - Math.getExponent(x);
    return Math.scalb(Math.round(Math.scalb(x, exponent)), -exponent);
}

但是,Math.round(y)会返回long,因此不会保留InfinityNaN以及Math.abs(x) > Long.MAX_VALUE / Math.pow(2, exponent)的情况。此外,Math.round(y)始终围绕正无穷大(例如Math.round(0.5) == 1 && Math.round(1.5) == 2)。解决方案是使用Math.rint(y)接收double并保留无偏的IEEE 754舍入到最接近的规则(例如Math.rint(0.5) == 0.0 && Math.rint(1.5) == 2.0),即:

public static double reducePrecision(double x, int bits) {
    int exponent = bits - Math.getExponent(x);
    return Math.scalb(Math.rint(Math.scalb(x, exponent)), -exponent);
}

最后,这是一个确认我们期望的单元测试:

public static String decompose(double d) {
    int SIGN_WIDTH = 1;
    int EXP_WIDTH = 11;
    int SIGNIFICAND_WIDTH = 53;
    String s = String.format("%64s", Long.toBinaryString(Double.doubleToRawLongBits(d))).replace(' ', '0');
    return s.substring(0, 0 + SIGN_WIDTH) + " "
            + s.substring(0 + SIGN_WIDTH, 0 + SIGN_WIDTH + EXP_WIDTH) + " "
            + s.substring(0 + SIGN_WIDTH + EXP_WIDTH, 0 + SIGN_WIDTH + EXP_WIDTH + SIGNIFICAND_WIDTH - 1);
}

public static void test() {
    // Use a fixed seed so the generated numbers are reproducible.
    java.util.Random r = new java.util.Random(0);

    // Generate a floating point number that makes use of its full 52 bits of significand precision.
    double a = r.nextDouble() * 100;
    System.out.println(decompose(a) + " " + a);
    Assert.assertFalse(decompose(a).split(" ")[2].substring(23).equals(String.format("%0" + (52 - 23) + "d", 0)));

    // Cast the double to a float to produce a "ground truth" of precision loss to compare against.
    double b = (float) a;
    System.out.println(decompose(b) + " " + b);
    Assert.assertTrue(decompose(b).split(" ")[2].substring(23).equals(String.format("%0" + (52 - 23) + "d", 0)));
    // 32-bit float has a 23 bit significand, so c's bit pattern should be identical to b's bit pattern.
    double c = reducePrecision(a, 23);
    System.out.println(decompose(c) + " " + c);
    Assert.assertTrue(b == c);

    // 23rd-most significant bit in c is 1, so rounding it to the 22nd-most significant bit requires breaking a tie.
    // Since 22nd-most significant bit in c is 0, d will be rounded down so that its 22nd-most significant bit remains 0.
    double d = reducePrecision(c, 22);
    System.out.println(decompose(d) + " " + d);
    Assert.assertTrue(decompose(d).split(" ")[2].substring(22).equals(String.format("%0" + (52 - 22) + "d", 0)));
    Assert.assertTrue(decompose(c).split(" ")[2].charAt(22) == '1' && decompose(c).split(" ")[2].charAt(21) == '0');
    Assert.assertTrue(decompose(d).split(" ")[2].charAt(21) == '0');
    // 21st-most significant bit in d is 1, so rounding it to the 20th-most significant bit requires breaking a tie.
    // Since 20th-most significant bit in d is 1, e will be rounded up so that its 20th-most significant bit becomes 0.
    double e = reducePrecision(c, 20);
    System.out.println(decompose(e) + " " + e);
    Assert.assertTrue(decompose(e).split(" ")[2].substring(20).equals(String.format("%0" + (52 - 20) + "d", 0)));
    Assert.assertTrue(decompose(d).split(" ")[2].charAt(20) == '1' && decompose(d).split(" ")[2].charAt(19) == '1');
    Assert.assertTrue(decompose(e).split(" ")[2].charAt(19) == '0');

    // Reduce the precision of a number close to the largest normal number.
    double f = reducePrecision(a * 0x1p+1017, 23);
    System.out.println(decompose(f) + " " + f);
    // Reduce the precision of a number close to the smallest normal number.
    double g = reducePrecision(a * 0x1p-1028, 23);
    System.out.println(decompose(g) + " " + g);
    // Reduce the precision of a number close to the smallest subnormal number.
    double h = reducePrecision(a * 0x1p-1051, 23);
    System.out.println(decompose(h) + " " + h);
}

及其输出:

0 10000000101 0010010001100011000110011111011100100100111000111011 73.0967787376657
0 10000000101 0010010001100011000110100000000000000000000000000000 73.0967788696289
0 10000000101 0010010001100011000110100000000000000000000000000000 73.0967788696289
0 10000000101 0010010001100011000110000000000000000000000000000000 73.09677124023438
0 10000000101 0010010001100011001000000000000000000000000000000000 73.0968017578125
0 11111111110 0010010001100011000110100000000000000000000000000000 1.0266060746443803E308
0 00000000001 0010010001100011000110100000000000000000000000000000 2.541339559435826E-308
0 00000000000 0000000000000000000000100000000000000000000000000000 2.652494739E-315