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.
views:
6228answers:
6
+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
2009-06-03 13:22:05
+1: Works with Python 2.5: good!
EOL
2009-06-16 10:40:43
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
2010-01-26 13:18:57
+29
A:
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
2009-06-03 13:24:37
+5
A:
or compare the number to itself. NaN is always != NaN, otherwise (e.g. if it is a number) the comparison should succeed.
Tomalak
2009-06-03 13:24:51
For people stuck with python <= 2.5. Nan != Nan did not work reliably. Used numpy instead.
Bear
2010-01-18 07:06:20
+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
2010-01-26 09:10:53
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
2010-06-17 08:35:39