tags:

views:

6228

answers:

6

float('nan') results in a thingy simply called nan. But how do I check for it? Should be very easy, but i cannot find it.

+15  A: 

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

def isNaN(num):
    return num != num
Chris Jester-Young
+1: Works with Python 2.5: good!
EOL
Word of warning: quoting Bear's comment below "For people stuck with python <= 2.5. Nan != Nan did not work reliably. Used numpy instead." Having said that, I've not actually ever seen it fail.
mavnn
+29  A: 

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
>>>
gimel
+1 Win, a built-in function for doing this. :-)
Chris Jester-Young
new in version 2.6
gimel
just what I was looking for! Thx :)
Jack Ha
+5  A: 

math.isnan()

or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it is a number) the comparison should succeed.

Tomalak
For people stuck with python <= 2.5. Nan != Nan did not work reliably. Used numpy instead.
Bear
+7  A: 

numpy.isnan(float) tells you if it's NaN or not in Python 2.5

mavnn
Thanks, stuck with 2.5, this is just what I needed
wich
+2  A: 

Another method if you're stuck on <2.6, you don't have numpy, and you don't have IEEE 754 support:

def isNaN(x):
    return str(x) == str(1e400*0)
jleedev
A: 

With python < 2.6 I ended up with

def isNaN(x):
    return str(float(x)).lower() == 'nan'

This works for me with python 2.5.1 on a Solaris 5.9 box and with python 2.6.5 on Ubuntu 10

Mauro Bianchi