【发布时间】:2009-11-12 23:55:45
【问题描述】:
我正在查看 Java 标准库 (6) 中 compare(double, double) 的实现。上面写着:
public static int compare(double d1, double d2) {
if (d1 < d2)
return -1; // Neither val is NaN, thisVal is smaller
if (d1 > d2)
return 1; // Neither val is NaN, thisVal is larger
long thisBits = Double.doubleToLongBits(d1);
long anotherBits = Double.doubleToLongBits(d2);
return (thisBits == anotherBits ? 0 : // Values are equal
(thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN)
1)); // (0.0, -0.0) or (NaN, !NaN)
}
这个实现的优点是什么?
编辑:“优点”是一个(非常)糟糕的词选择。我想知道这是如何工作的。
【问题讨论】:
-
与此相关以及此处的所有讨论:查看浮点比较领域的 JDK 可怕之处:publicobject.com/2009/11/floating-point-equality.html
-
@KevinBourrillion - 按照我的阅读方式,这实际上是关于 IEE 浮点标准的可怕之处。 Java 必须按照 IEE 标准运行,因为这是现代机器上的硬件实现的。
标签: java comparison floating-point