28

Why am I getting the following:

>>> v
nan
>>> type(v)
<type 'numpy.float64'>
>>> v == np.nan
False
>>> np.isnan(v)
True

I would have thought the two should be equivalent?

Alexander McFarlane
  • 10,643
  • 9
  • 59
  • 100
  • 2
    Also see: http://stackoverflow.com/a/1573715/325565 (not directly python-related, but written by a member of the IEEE-754 committee that defined why this is the way it is) – Joe Kington Apr 09 '15 at 01:27
  • 2
    I guess it makes sense that two undefined values cannot be compared as identical because they are by definition undefined. Just a little confusing when you get a nan != nan error the first time! – Alexander McFarlane Apr 09 '15 at 01:31
  • 1
    related: http://stackoverflow.com/q/13003202/674039 – wim Apr 09 '15 at 01:32

1 Answers1

32

nan != nan. That's just how equality comparisons on nan are defined. It was decided that this result is more convenient for numerical algorithms than the alternative. This is specifically why isnan exists.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Thanks! That thoroughly confused me for a while when debugging :) – Alexander McFarlane Apr 09 '15 at 01:25
  • By the way, this is likely due to IEEE 754 which states: *Four mutually exclusive relations are possible: less than, equal, greater than, and unordered. The last case arises when at least one operand is NaN. Every NaN shall compare unordered with everything, including itself.* Edit: Looks like I was beaten by ~2 hours by a comment with a link that goes into more detail -- see Joe Kington's comment to the question. – jedwards Apr 09 '15 at 03:59