首页 > 解决方案 > Why does my Python freeze when I do an overflow calculation?

问题描述

I'm a MATLAB user trying to understand Python so sorry if this is obvious.

If I say

print(9**9)

I get: 387420489

Great.

If I say print(9**9**9) Python just sits there indefinitely and freezes (I use Spyder version 4). Ctrl-C doesn't stop it. Why does it not just immediately return Inf? Is this expected behavior?

标签: pythonmathfreeze

解决方案


在使用整数进行数值计算时,python不限于机器特定的数字,例如“int32”,因此“2147483647”这样的数字对它没有多大意义。相反,它使用“大整数”库,原则上,只要有足够的内存,它就可以表达任何大数。当面对诸如9**9**9python 之类的计算时,试图准确地执行它产生准确的结果,无论它有多大。对于这个特定的计算,它只需要很多时间(和内存,大概在内部 python 正在尝试根据需要分配越来越多的内存)。


推荐阅读