在哪种情况下,“a!= a”可以返回“true”?

时间:2013-08-27 08:19:31

标签: java numbers equality nan

java.lang.Math#min(double, double)

public static double min(double a, double b) {
    if (a != a) return a; // a is NaN
    if (a == 0.0d && b == 0.0d && Double.doubleToLongBits(b) == negativeZeroDoubleBits) return b;
    return (a <= b) ? a : b;
}

在哪种情况下,a != a可以返回true?似乎a是NaN,但我无法想象一个例子。你能提供一个吗?

2 个答案:

答案 0 :(得分:10)

一个简单的例子是

double d = Double.NaN; // or
double d = 0.0/0.0; // or
double d = Double.POSITIVE_INFINITY + Double.NEGATIVE_INFINITY;
if (Double.isNaN(a)) { // tests if a != a
   // do something

BTW Double.compare()确实看到NaN等于

if (Double.compare(d, d) == 0) // always.

对于任何类型和值,都可以使用多个线程。 e.g。

if (a != /* another thread changes 'a' */ a) {
    // a thread changed a while you were looking at it.

答案 1 :(得分:0)

如果a是NAN,则NAN例如除以零

min(0.0f/0.0f, 0.0f)