简体   繁体   中英

python “is” returns True but “==” returns False

shouldn't "==" return True as long as "is" returns True?

In [101]: np.NAN is np.nan is np.NaN
Out[101]: True

In [102]: np.NAN == np.nan 
Out[102]: False

In [103]: np.NaN == np.nan
Out[103]: False

In [104]: np.NaN == np.NAN
Out[104]: False

EDIT:

Are the 3 expressions for float nan just legacy of old numpy versions or do they have other usage?

No, not for NaN . You have found one of the exceptions. According to IEEE 754 , NaN is not equal to anything, not even itself:

A comparison with a NaN always returns an unordered result even when comparing with itself.

Not just numpy behaves like this:

>>> nan = float('nan')
>>> nan is nan
True
>>> nan == nan
False

as will any programming language that implements floating point arithmetic according to the IEEE standard.

The multiple spellings are there to match the common capitalisations for the name. It is an abbreviation for Not a Number and different people capitalise the abbreviation differently.

is is always going to be True for the same object, but == is not even guaranteed to return a boolean. From the __eq__ documentation :

By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (eg, in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.

The standard for floating point (IEEE 754) requires that any comparison of NaN values returns not equal. This is common to any programming language that claims to implement IEEE 754, not just Python.

See also Wikipedia's description of a NaN .

Quoting from the docs ,

Special values defined in numpy: nan, inf,

NaNs can be used as a poor-man's mask (if you don't care what the original value was)

Note: cannot use equality to test NaNs. Eg:

...

np.nan == np.nan # is always False! Use special numpy functions instead. False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM