numpy.isnan(value) not the same as value == numpy.nan?

23,506

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.

Share:
23,506

Related videos on Youtube

Alexander McFarlane
Author by

Alexander McFarlane

I'm pretty average at snowboarding Quantitative researcher designing prop trading strategies in python Random Quotes If a man does not have to work: If he does not grow crops or hunt or do something, he very quickly destroys himself - Yaka Garimala, quoting an Aboriginal saying Physics Nobel Laureate Quotes Physics is like sex: sure, it may give some practical results, but that's not why we do it - Richard Feynman All science is either physics or stamp collecting - Ernest Rutherford Anyone who has never made a mistake has never tried anything new - Albert Einstein Because of its extreme complexity, most physicists will be glad to see the end of QED - Paul Dirac

Updated on April 09, 2020

Comments

  • Alexander McFarlane
    Alexander McFarlane about 4 years

    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?

    • Joe Kington
      Joe Kington about 9 years
      Also see: 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)
    • Alexander McFarlane
      Alexander McFarlane about 9 years
      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!
    • wim
      wim about 9 years
  • Alexander McFarlane
    Alexander McFarlane about 9 years
    Thanks! That thoroughly confused me for a while when debugging :)
  • jedwards
    jedwards about 9 years
    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.