我正在研究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)
}
Run Code Online (Sandbox Code Playgroud)
这个实现的优点是什么?
编辑:"优点"是一个(非常)糟糕的选择.我想知道它是如何工作的.
你如何向仍然认为计算机是无限智能和准确的新鲜程序员和外行人解释浮点不准确?
你有一个最喜欢的例子或轶事似乎比一个精确但干燥的解释更好地理解这个想法吗?
这是如何在计算机科学课程中教授的?