Skip to content
scipython.com

Q10.1.5Checking for nan without using isnan

How could you establish whether a floating point number is nan or not without using math.isnan or numpy.isnan?

Show solution

We cannot compare with == since nan is not equal to itself. However, it is the only floating point number which is not equal to itself, so use != instead:

In [x]: c = 0 * 1.e1000    # 0 * inf is nan
In [x]: c != c
Out[x]: True               # c isn't equal to itself, so must be nan