gpt4 book ai didi

java - 为什么 Java 的 Double.compare(double, double) 是这样实现的?

转载 作者:IT老高 更新时间:2023-10-28 20:54:44 24 4
gpt4 key购买 nike

我正在查看 compare(double, double) 的实现在 Java 标准库 (6) 中。上面写着:

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)
}

这个实现的优点是什么?


编辑:“优点”是一个(非常)糟糕的词选择。我想知道这是如何工作的。

最佳答案

解释在代码的注释中。 Java 对 0.0-0.0 以及“非数字”(NaN)都有 double 值。您不能对这些值使用简单的 == 运算符。查看 doubleToLongBits() 源代码和 the Javadoc for the Double.equals() method :

Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if

d1.doubleValue() == d2.doubleValue()

also has the value true. However, there are two exceptions:

  • If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN == Double.NaN has the value false.
  • If d1 represents +0.0 while d2 represents -0.0, or vice versa, the equal test has the value false, even though +0.0 == -0.0 has the value true.

This definition allows hash tables to operate properly.

关于java - 为什么 Java 的 Double.compare(double, double) 是这样实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1726254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com