What does float("NaN") and float("inf") mean in Python?

Question:

I've seen code like this:

def _min(*args):
    res = float('inf')
    for value in args:
        if value < res:
            res = value
    return res

I would like to know what is a float("inf") and a float("NaN").

Answer:

Infinite

As already commented, float("inf") will create an infinite number:

>>> float("inf")
inf

Which is actually equivalent to math.inf :

>>> import math
>>> math.inf
inf
>>> float("inf") == math.inf
True

It also has the counterpart of -infinite:

>>> float("-inf")
-inf
>>> -float("inf")
-inf

It is important to note that any number is less than infinity, just as any number is greater than -infinity.

There is also a function in math to know if it is infinite, which is called isinf

>>> math.isinf(float("inf"))
True
>>> math.isinf(float("-inf"))
True
>>> math.isinf(3421)
False

NaN

NaN stands for Not a Number which means it is not a number. There are a few different ways to get to this value. One of them is the one you saw with float("NaN") :

>>> float("NaN")
nan

Another would be subtracting infinity from infinity:

>>> float("inf") - float("inf")
nan

Any arithmetic operation on a nan will still give a nan :

>>> float("nan") * 5
nan

It also has the isnan function that tests if it is nan :

>>> math.isnan(float("nan"))
True
>>> math.isnan(25)
False

Additional reading from inf - inf :

Scroll to Top