为什么 Double.compare() 比较数字两次
Why does Double.compare() compares the numbers twice
我在调试模式下通过 F5
查看 Double.compare()
实现(复制粘贴)
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
// Cannot use doubleToRawLongBits because of possibility of NaNs.
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)
}
我期待的是
public static int compare(double d1, double d2) {
if (d1 < d2)
return -1;
if (d1 > d2)
return 1;
return 0;
}
但不是 return 0;
该方法将双精度数转换为位,如果其中一个比另一个大,则再次比较
thisBits < anotherBits ? -1 : 1);
为什么第二次比较是冗余的?
如果 d1
是像 0.0
这样的数字,而 d2
是 NaN
,那么 d1 < d2
将为假,而 d1 > d2
将为 也为假,但这并不会使NaN
等于d1
。此外,如果 d1
是 -0.0
并且 d2
是 0.0
,那么 d1 < d2
将是 false
而 d1 > d2
将是 也是假的,但是0.0
应该大于-0.0
。
评论说得很清楚了。
我在调试模式下通过 F5
查看 Double.compare()
实现(复制粘贴)
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
// Cannot use doubleToRawLongBits because of possibility of NaNs.
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)
}
我期待的是
public static int compare(double d1, double d2) {
if (d1 < d2)
return -1;
if (d1 > d2)
return 1;
return 0;
}
但不是 return 0;
该方法将双精度数转换为位,如果其中一个比另一个大,则再次比较
thisBits < anotherBits ? -1 : 1);
为什么第二次比较是冗余的?
如果 d1
是像 0.0
这样的数字,而 d2
是 NaN
,那么 d1 < d2
将为假,而 d1 > d2
将为 也为假,但这并不会使NaN
等于d1
。此外,如果 d1
是 -0.0
并且 d2
是 0.0
,那么 d1 < d2
将是 false
而 d1 > d2
将是 也是假的,但是0.0
应该大于-0.0
。
评论说得很清楚了。