相关疑难解决方法(0)

为什么Java的Double.compare(double,double)实现方式如何呢?

我正在研究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)

这个实现的优点是什么?


编辑:"优点"是一个(非常)糟糕的选择.我想知道它是如何工作的.

java floating-point comparison

35
推荐指数
2
解决办法
5万
查看次数

浮点不准确的例子

你如何向仍然认为计算机是无限智能和准确的新鲜程序员和外行人解释浮点不准确?
你有一个最喜欢的例子或轶事似乎比一个精确但干燥的解释更好地理解这个想法吗?
这是如何在计算机科学课程中教授的?

floating-point floating-accuracy

29
推荐指数
3
解决办法
10万
查看次数