In which case could “a != a” return “true”?

这一生的挚爱 提交于 2019-11-28 08:54:56

问题


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

In which case could a != a return true? It seems that it's when a is NaN, but I can't imagine an example. Could you please provide one?


回答1:


A simple example is

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() does see NaN as equal

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

With multiple threads this is possible for any type and value. e.g.

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



回答2:


If a is NAN, and NAN is for example divide by zero

min(0.0f/0.0f, 0.0f)



来源:https://stackoverflow.com/questions/18460416/in-which-case-could-a-a-return-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!