1

I was looking at the Math sources in the Android Framework and here is what the round() method looks like :

public static int round(float f) {
    // check for NaN
    if (f != f) {
        return 0;
    }
    return (int) floor(f + 0.5f);
}

I'm trying to wrap my head around what the first check does without success. How could f be different from itself ? I also can't think of any test case that would make this any different... Any idea ?

Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
ben
  • 1,151
  • 10
  • 20
  • 1
    See [JLS 15.21.1](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.21.1). That's just how it's defined. – ajb Feb 18 '14 at 01:52

2 Answers2

0

How could f be different from itself?

If f is a NaN it will test as different from all floats including another NaN. That's the definition. From JLS #15.21.1:

"If either operand is NaN, then the result of == is false but the result of != is true. Indeed, the test x!=x is true if and only if the value of x is NaN."

I also can't think of any test case that would make this any different... Any idea?

Err, Float.NaN.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • I find this a bit confusing but I guess it makes sense. Thanks EJP, will mark the answer as accepted when possible – ben Feb 18 '14 at 01:58
  • @downvoter You're arguing with the JLS here. If you have an over-riding citation please provide it. – user207421 Jul 03 '14 at 06:50
0

NaN is the only variable for which x != x holds true. Take a look at this answer for more details.

Community
  • 1
  • 1
Chthonic Project
  • 8,216
  • 1
  • 43
  • 92
  • Thanks! This thread definitely made it easier for me to understand the reason why it's how it works – ben Feb 18 '14 at 01:59