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

2022-08-31 04:15:13

在以下程序中,您可以看到每个略小于的值都向下舍入,但 ..50.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 更新 31。


答案 1

总结

在 Java 6(以及可能更早的版本)中,实现为 .1 这是一个规范错误,正是针对这一个病理案例。2 Java 7 不再强制要求这种破碎的实现。3 个round(x)floor(x+0.5)

问题

0.5+0.499999999999999994 正好是双精度 1:

static void print(double d) {
    System.out.printf("%016x\n", Double.doubleToLongBits(d));
}

public static void main(String args[]) {
    double a = 0.5;
    double b = 0.49999999999999994;

    print(a);      // 3fe0000000000000
    print(b);      // 3fdfffffffffffff
    print(a+b);    // 3ff0000000000000
    print(1.0);    // 3ff0000000000000
}

这是因为 0.49999999999999999994 的指数小于 0.5,因此当它们相加时,其尾数会移位,ULP 会变大。

解决方案

从Java 7开始,OpenJDK(例如)实现了它:4

public static long round(double a) {
    if (a != 0x1.fffffffffffffp-2) // greatest double value less than 0.5
        return (long)floor(a + 0.5d);
    else
        return 0;
}

1. http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round%28double%29

2. http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6430675(@SimonNickerson找到这个的功劳)

3. http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#round%28double%29

4. http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/lang/Math.java#Math.round%28double%29


答案 2

这似乎是一个已知的错误(Java错误6430675:Math.round对0x1.fffffffp-2有令人惊讶的行为),该错误已在Java 7中修复。