Why numpy.nan is different than math.nan?
Asked Answered
F

1

5

Why is math.nan different than numpy.nan?

>>> import math
>>> import numpy as np
>>> math.nan is math.nan
True
>>> np.nan is np.nan
True
>>> np.nan is math.nan
False

What is the point of having two different NaNs?

Freeholder answered 5/7, 2021 at 12:20 Comment(6)
They were created separately, so they're separate objects. They have the same value (even if that value is not equal to itself).Leopoldine
It gets worse than that: np.nan == np.nan returns False.Pristine
NaN is not a singleton. NaN is a bit pattern that has a special interpretation (actually, there are many different NaNs, since a NaN can have a "payload"). There can be multiple instances of the same NaN, just like there can be multiple instances of, say, 1.0. Try this: x = 1.0; y = 1.0; print(x is y). The output is False.Amphibolous
@Pristine Also math.nan == math.nan also returns False.Franconian
And float('NaN') == float('NaN') also returns False, although I don't know if that differs from math.nan is implemented.Franconian
NaN == NaN should return false. That's how NaN behavior is defined in IEEE 754 and most languages that use it. Like, "NaN is not equal to any numeric value, including other NaNs". It's "three-valued logic", like SQL NULLs. Related to how Warren talks about NaNs being a class of values, not just one specific value or bit pattern. Need to use isnan() tests and compare those results if you want to see if two values are both NaNs.Cadence
R
8

What is the point of having two different NaNs?

Disclaimer: I assume you want to know why there is math.nan and numpy.nan, if this does not hold true ignore this answer entirely.

This is due to historical reasons, math docs inform that math.nan is

New in version 3.5.

NumPy is older than that, PyPI NumPy release history shows that version 1.0 was released in October 2006, whilst according to PEP 478 first final version for Python 3.5.0 was scheduled for September 2015, therefore creators of NumPy have not possibility of usage of math.nan. This lead to question why nan was added to math if it is already in numpy. This might be explained simply: math is built-in module, whilst numpy is not.

As side note you might also craft NaN without any imports in python, just do float("NaN").

Recycle answered 5/7, 2021 at 12:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.