Search code examples
pythonmathinfinity

Why is math.inf a float and why can't I convert it to an integer?


I was doing some experimenting, and I was trying to do this:

import math
for i in range(math.inf):
    print(i)

I expected it to be exactly thesame as this:

c = 0
while True:
    print(c)
    c += 1

But it went more like this

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Then I tried converting the inf to an int:

import math
for i in range(int(math.inf)):
    print(i)

But that gave me this error saying you can't convert float infinity to an integer.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: cannot convert float infinity to integer

Now my question is why this happens and why infinity is a float in the first place. Is it because of some underlying mathematical law or is this a solution to some problem that arose from doing it otherwise?

Thanks in advance!


Solution

  • infinity is not an integer.

    math.inf is equivelent to float('inf') and is a floating point feature implemented in compliance of IEEE 754 (in addition to NaN values and such). From the Python update summaries:

    Many floating-point features were added. The float() function will now turn the string nan into an IEEE 754 Not A Number value, and +inf and -inf into positive or negative infinity. This works on any platform with IEEE 754 semantics. (Contributed by Christian Heimes; issue 1635.)


    However, if you want to iterate over the natural numbers, you can use a builtin generator in itertools, count.

    import itertools
    natural_numbers = itertools.count()
    
    for n in natural_numbers:
        ...
    

    or you can iterate over ℤ+ with itertools.count(1) ;)