2

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 a float:

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!

  • Partly because on traditional platform, an integer can only be as large as the number of bits per registers that are available inside CPUs, thus they overflow. In terms of data structures, IEEE floats were designed to "represent" inf in a particular way. However, mathematically, infinity is actually of a different type and thus it isn't a number, so it cannot actually be an integer. In [this answer I gave in this thread](https://stackoverflow.com/a/54849261/2904896), a different user had a similar but different issue to yours which may be of interests. – metatoaster May 02 '19 at 23:39

2 Answers2

6

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) ;)

modesitt
  • 7,052
  • 2
  • 34
  • 64
3

math.inf is not a specific value; it's a special identifier, more on the order of nan than a value. It is defined as a float for greatest usage in marking a value that requires special treatment. It's semantic definition is that it's greater than any expressible value: it's infinity. You can't cast it to int because there is no defined equivalent.

You might want to use the constant sys.maxint for your purposes. See here for extra details.

Prune
  • 76,765
  • 14
  • 60
  • 81