0"? In my Python interpreter, I get: >>> float('nan') > 0 False but is this guaranteed? If I u..." /> 0"? In my Python interpreter, I get: >>> float('nan') > 0 False but is this guaranteed? If I u..." /> 0"? In my Python interpreter, I get: >>> float('nan') > 0 False but is this guaranteed? If I u..."/>

Does Python define the value of "NaN > 0"?

403 views Asked by At

Does Python defined the value of "NaN > 0"? In my Python interpreter, I get:

>>> float('nan') > 0
False

but is this guaranteed?

If I understand correctly, the IEEE 754 standard assigns False to any comparison involving NaN. However, I can't find anything in the Python documentation that indicates that this standard is followed. I even understand that 1/0 should give infinity, under IEEE 754, but Python raises an exception (ZeroDivisionError), so Python does not fully follow IEEE 754.

So, is the result of float('nan') > 0 fully defined in Python? I need to know whether it is the same on all platforms, and with all versions of Python (including old ones).

3

There are 3 answers

0
NPE On BEST ANSWER

All Python implementations that I've used on various platforms use IEEE-754 and would behave as you describe.

However, this does not appear to be formally mandated by the language. So much so that the tutorial has the following to say (emphasis mine):

Almost all machines today (July 2010) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 “double precision”.

Here is a relevant thread from 2008: Python on non IEEE-754 platforms: plea for information.

It is very easy to check whether your interpreter/platform behave the way you expect. If you're critically dependent on this, you could easily detect non-compliance when your program starts up.

3
mgilson On

I think that's a pretty safe assumption. The math library documentation implies that python's NaN should act as specified in IEEE 754.

Of course, if you're really paranoid about it, you could write a UnitTest and then if you ever do find a system where that doesn't hold, at least you'll know immediately.

1
shshank On

This link suggests that, the NaN concept was incorporated in python from version 2.3. So it should be same on all platforms in the currently used versions.

It also has an implementation in math library.

e.g. math.isnan()

Checks if the float x is a NaN (not a number).
NaNs are part of the IEEE 754 standards. Operation like but not limited to
inf * 0, inf / inf or any operation involving a NaN, e.g. nan * 1, return a NaN.


New in version 2.6.

>>> import math
>>> x=float('nan')
>>> math.isnan(x)
True
>>>