在 Python 3.6.2、Win10-x64 上
只是我遇到的一些奇怪的事情,无法解释。
在:
x = 10.0
for i in range(10):
print(str(i) + " | " + str(x))
x *= x
输出:
0 | 10.0
1 | 100.0
2 | 10000.0
3 | 100000000.0
4 | 1e+16
5 | 1e+32
6 | 1.0000000000000002e+64
7 | 1.0000000000000003e+128
8 | 1.0000000000000005e+256
9 | inf
怎么就变成了inf
?为什么不抛出异常呢?
例如,如果我用 **=
替换最后一行中的 *=
,那么在第二次迭代时它会引发 OverflowError: (34, '结果太大')
,这是有道理的(因为它只是 10.000.000.000^10.000.000.000)。
这是否意味着对 float 有一种“软”限制——超过时——将它们变成 inf
?如果是这样,那个限制是什么,无论算术运算如何,它都是一样的吗?这难道不意味着类似 inf == this_limit + anything
的东西吗?
.
添加:
我知道有 sys.float_info.max
。这是极限吗?
我刚刚有了一个想法并测试了一些东西:
print(sys.float_info.max)
print(sys.float_info.max + 1)
print(sys.float_info.max * 2)
print(sys.float_info.max * 1.000000000000001)
print(sys.float_info.max * 1.0000000000000001)
这给了我:
1.7976931348623157e+308
1.7976931348623157e+308
inf
inf
1.7976931348623157e+308
这对我来说很奇怪......
最佳答案
How come it just turns into inf?
因为结果对于最大的有限 float 来说太大了,所以会溢出。
Why doesn't it throw an exception?
因为 Python 对何时将 inf/nan 转换为异常不是很一致。一些操作给出异常(exception)。有些给 inf/nan。
Does this mean that there is a kind of "soft" limit on floats that -- when exceeded -- turns them into inf? And if so, what is that limit and is it the same regardless of the arithmetic operation? And wouldn't that imply something like inf == this_limit + anything?
任何在四舍五入后大于 1.7976931348623157e+308 的结果都会变成一个 inf(或者一个异常,如果 Python 喜欢的话)。确切的限制不能用 float 表示;您实际上不能执行 this_limit + anything
,因为尝试将 this_limit
放入 float 中会将其四舍五入为 1.7976931348623157e+308。
关于Python:一个大的 float 怎么会自动变成 *inf*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46432189/