为什么math.inf是浮点数,为什么不能将其转换为整数?

Mat*_*lde 2 python math infinity

我正在做一些实验,并且正在尝试这样做:

import math
for i in range(math.inf):
    print(i)
Run Code Online (Sandbox Code Playgroud)

我希望它与此完全相同:

c = 0
while True:
    print(c)
    c += 1
Run Code Online (Sandbox Code Playgroud)

但它更像这样

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

然后,我尝试将转换inf为浮点数:

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

但这给了我这个错误,表明您不能将float infinity转换为整数。

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

现在我的问题是为什么会发生这种情况,以及为什么无穷大首先是浮点数。是因为某些基本的数学法则还是这是对否则执行某些问题的解决方案?

提前致谢!

mod*_*itt 5

无限不是整数

math.inf等效于float('inf')浮点功能,并且是符合IEEE 754(除了NaN值等)的浮点功能。从Python更新摘要中:

增加了许多浮点功能。float()函数现在将把字符串nan转换为IEEE 754非数字值,并将+ inf和-inf转换为正或负无穷大。这可以在具有IEEE 754语义的任何平台上使用。(由Christian Heimes贡献;版本1635。)


但是,如果要迭代?而不使用while循环,生成器的魔力可以助您一臂之力。

import itertools
natural_numbers = itertools.count()

for n in natural_numbers:
    ...
Run Code Online (Sandbox Code Playgroud)

或者你可以用itertools.count(1);)遍历?+