33

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?

3
  • 2
    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) Commented Apr 9, 2015 at 1: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! Commented Apr 9, 2015 at 1:31
  • 1
    related: stackoverflow.com/q/13003202/674039 Commented Apr 9, 2015 at 1:32

1 Answer 1

35

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That thoroughly confused me for a while when debugging :)
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.