How can I check for NaN values?


Question

float('nan') results in Nan (not a number). But how do I check for it? Should be very easy, but I cannot find it.

1
799
10/7/2018 7:50:30 PM

Accepted Answer

math.isnan(x)

Return True if x is a NaN (not a number), and False otherwise.

>>> import math
>>> x = float('nan')
>>> math.isnan(x)
True
1031
7/22/2019 11:42:49 AM

The usual way to test for a NaN is to see if it's equal to itself:

def isNaN(num):
    return num != num

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon