Mathis Van Eetvelde
Mathis Van Eetvelde

Reputation: 362

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!

Upvotes: 2

Views: 2568

Answers (2)

modesitt
modesitt

Reputation: 7210

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

Upvotes: 7

Prune
Prune

Reputation: 77837

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.

Upvotes: 3

Related Questions