[python] What is inf and nan?

Just a question that I'm kind of confused about

So I was messing around with float('inf') and kind of wondering what it is used for.

Also I noticed that if I add -inf + inf i get nan is that the same as Zero or not.

I'm confused about what the uses of these two values are.

Also when I do nan - inf I don't get -inf I get nan I'm sure it's all pretty simple but I stumbled upon them and didn't know what they do.

This question is related to python python-2.7

The answer is


Inf is infinity, it's a "bigger than all the other numbers" number. Try subtracting anything you want from it, it doesn't get any smaller. All numbers are < Inf. -Inf is similar, but smaller than everything.

NaN means not-a-number. If you try to do a computation that just doesn't make sense, you get NaN. Inf - Inf is one such computation. Usually NaN is used to just mean that some data is missing.


I use inf/-inf as initial values to find minimum/maximum value of a measurement. Lets say that you measure temperature with a sensor and you want to keep track of minimum/maximum temperature. The sensor might provide a valid temperature or might be broken. Pseudocode:

# initial value of the temperature
t = float('nan')          
# initial value of minimum temperature, so any measured temp. will be smaller
t_min = float('inf')      
# initial value of maximum temperature, so any measured temp. will be bigger
t_max = float('-inf')     
while True:
    # measure temperature, if sensor is broken t is not changed
    t = measure()     
    # find new minimum temperature
    t_min = min(t_min, t) 
    # find new maximum temperature
    t_max = max(t_max, t) 

The above code works because inf/-inf/nan are valid for min/max operation, so there is no need to deal with exceptions.


nan means "not a number", a float value that you get if you perform a calculation whose result can't be expressed as a number. Any calculations you perform with NaN will also result in NaN.

inf means infinity.

For example:

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

You say:

when i do nan - inf i dont get -inf i get nan

This is because any operation containing NaN as an operand would return NaN.

A comparison with NaN would return an unordered result.

>>> float('Inf') == float('Inf')
True
>>> float('NaN') == float('NaN')
False