为什么Math.round(0.49999999999999994)返回1?

在下面的程序中,您可以看到.5除以外的每个值都略小于四舍五入的值0.5。


for (int i = 10; i >= 0; i--) {

    long l = Double.doubleToLongBits(i + 0.5);

    double x;

    do {

        x = Double.longBitsToDouble(l);

        System.out.println(x + " rounded is " + Math.round(x));

        l--;

    } while (Math.round(x) > i);

}

版画


10.5 rounded is 11

10.499999999999998 rounded is 10

9.5 rounded is 10

9.499999999999998 rounded is 9

8.5 rounded is 9

8.499999999999998 rounded is 8

7.5 rounded is 8

7.499999999999999 rounded is 7

6.5 rounded is 7

6.499999999999999 rounded is 6

5.5 rounded is 6

5.499999999999999 rounded is 5

4.5 rounded is 5

4.499999999999999 rounded is 4

3.5 rounded is 4

3.4999999999999996 rounded is 3

2.5 rounded is 3

2.4999999999999996 rounded is 2

1.5 rounded is 2

1.4999999999999998 rounded is 1

0.5 rounded is 1

0.49999999999999994 rounded is 1

0.4999999999999999 rounded is 0

我正在使用Java 6 update 31。


潇湘沐
浏览 851回答 3
3回答

守候你守候我

JDK 6中的源代码:public static long round(double a) {    return (long)Math.floor(a + 0.5d);}JDK 7中的源代码:public static long round(double a) {    if (a != 0x1.fffffffffffffp-2) {        // a is not the greatest double value less than 0.5        return (long)Math.floor(a + 0.5d);    } else {        return 0;    }}当值为0.49999999999999994d时,在JDK 6中,它将调用floor,因此返回1,但在JDK 7中,if条件是检查该数字是否为小于0.5的最大double值。由于在这种情况下,该数字不是小于0.5的最大double值,因此该else块返回0。您可以尝试0.49999999999999999d,它将返回1,但不会返回0,因为这是小于0.5的最大double值。

慕的地8271018

我在32位的JDK 1.6上具有相同的功能,但是在Java 7 64位的上,对于0.49999999999999994则具有0,其四舍五入为0,并且不打印最后一行。这似乎是VM的问题,但是,使用浮点运算,您应该期望在各种环境(CPU,32位或64位模式)下结果会有所不同。并且,当使用round或求逆矩阵等时,这些位会产生很大的不同。x64输出:10.5 rounded is 1110.499999999999998 rounded is 109.5 rounded is 109.499999999999998 rounded is 98.5 rounded is 98.499999999999998 rounded is 87.5 rounded is 87.499999999999999 rounded is 76.5 rounded is 76.499999999999999 rounded is 65.5 rounded is 65.499999999999999 rounded is 54.5 rounded is 54.499999999999999 rounded is 43.5 rounded is 43.4999999999999996 rounded is 32.5 rounded is 32.4999999999999996 rounded is 21.5 rounded is 21.4999999999999998 rounded is 10.5 rounded is 10.49999999999999994 rounded is 0
打开App,查看更多内容
随时随地看视频慕课网APP