0

I'm expecting Double.NaN - Double.NaN to be equal to 0, but it is NOT.

Could someone explain what's going on? What are the rules of thumb when it comes to doing maths on NaN? Is it something like "if any of the sub-expr is NaN, then the whole expr is NaN"?

thanks,

One Two Three
  • 22,327
  • 24
  • 73
  • 114
  • 9
    NaN is, quite literally, *not a number*. You can't do arithmetic on it. – Oliver Charlesworth Sep 22 '14 at 22:13
  • 2
    Even NaN==NaN returns false (and so has special methods to test for NaN. Basically NaN is "I dunno". What is "I dunno" minus "I dunno". It could be 6, 5, infinity. So its still "I dunno" – Richard Tingle Sep 22 '14 at 22:14
  • 1
    Not that even something like infinity-inifinity is still undefined... Not to mention 'I dunno' explained earlier ;) – dominik4142 Sep 22 '14 at 22:15
  • I've marked it as a duplicate; the question isn't *identical*, but is conceptually the same (x == x is the same as x - x == 0), and at any rate is covered by the accepted answer. – Oliver Charlesworth Sep 22 '14 at 22:18

1 Answers1

6

NaN stands for Not a Number, that's why NaN - NaN = NaN. Imagine something like this:

"foo" - "bar" = ??? <-- What should be the output?

Or

"foo" - (new Object()) = ??? <-- none of them are numbers

A more mathematical example on this:

0 / 0 = NaN <-- Mathematically we don't know the exact result

So, having something like this:

0 / 0 - 0 / 0 = NaN

More info:

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332