Skip to content

nans and object identity #395

@sjmillius

Description

@sjmillius

Description

nans (like float("nan"), np.nan) follow the IEEE 754 standard for floating-point arithmetic, which specifies that NaN is not equal to anything, including itself, so:

np.nan == np.nan  # False
float("nan") == float("nan") # False

But

np.nan is np.nan  # True

So these are objects that are not equal but identical to themselves. This leads to unexpected results in cases where object identity is taken as a short cut before equality comparisons, e.g. in tuples.

Snippet preview

>>> import numpy as np
>>> np.nan == np.nan
False
>>> (np.nan, np.nan) == (np.nan, np.nan)
True
>>> nan1 = float('nan'); nan2 = float('nan')
>>> nan1 == nan2
False
>>> (nan1, nan2) == (nan1, nan2)
True
>>> (nan1, nan2) == (nan2, nan1)
False

Checklist before calling for maintainers

  • Have you checked to ensure there aren't other open Issues for the same update/change?
  • Have you checked that this snippet is not similar to any of the existing snippets?
  • Have you added an Explanation section? It shall include the reasons for changes and why you'd like us to include them

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions