8 Answers
8

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.

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.
–
mavnnJan 26 '10 at 13:18

5

I'm sure that, given operator overloading, there are lots of ways I could confuse this function. go with math.isnan()
–
djsadinoffAug 11 '11 at 22:38

1

It says in the 754 spec mentioned above that NaN==NaN should always be false, although it is not always implemented as such. Isn't is possible this is how math and/or numpy check this under the hood anyway?
–
indienchildApr 1 '14 at 16:16

I actually just ran into this, but for me it was checking for nan, -inf, or inf. I just used

if float('-inf') < float(num) < float('inf'):

This is true for numbers, false for nan and both inf, and will raise an exception for things like strings or other types (which is probably a good thing). Also this does not require importing any libraries like math or numpy (numpy is so damn big it doubles the size of any compiled application).

It was probably downvoted because isnan() takes a float, not a string. There's nothing wrong with the function, and the problems are only in his attempted use of it. (For that particular use case his solution is valid, but it's not an answer to this question.)
–
Peter HansenJul 7 '13 at 14:12

1

Be careful with checking for types in this way. This will not work e.g. for numpy.float32 NaN's. Better to use a try/except construction: def is_nan(x): try: return math.isnan(x) except: return False
–
RobMar 24 '14 at 10:25