Python:巨大幂运算陷入困境,但不会引发错误 [英] Python: Huge Exponentiation Gets STUCK, but DOESN'T Raise An Error
问题描述
我在Win10 x64上使用Python 3.6。
I am using Python 3.6 on Win10 x64.
print(10**10**10**10)
这不是引发错误吗?当我运行此程序时,它什么也不会打印,但不会出现任何错误。没有OverflowError,没有MemoryError,什么也没有。现在已经运行了大约10分钟。我认为,它正在忙于计算?我怎么知道实际发生了什么?
Shouldn't this raise an Error? When I run this, it just doesn't print anything, but no error is raised. No OverflowError, no MemoryError, nothing. It has been running for like 10 minutes now. I assume, it is busy calculating? How can I find out, what is actually happening?
它还没有完成脚本。(即PyCharm没有显示退出代码0)为什么
It's not finishing the script. (i.e. PyCharm is not printing exit code 0) Why is that?
更普遍的是:
如果我遇到这种情况,该如何处理不知道预先涉及的计算量吗?我想避免脚本像永远那样卡住,而不会给我任何类型的错误。
How do I catch a situation like this, if I don't know the magnitude of the calculations involved in advance? I want to stop the script from getting stuck like this "forever" without giving me any sort of error to work with.
。
解决方案:
如以下Arthur Spoon所指出的,<$使用整数时,不会引发c $ c> OverflowError 。如果您想捕获太大而无法在合理的时间内进行计算错误,则在这些情况下仅显式使用浮点数是最容易的。
As pointed out by Arthur Spoon below, the OverflowError
is not raised when working with integers. If you want to be able to catch a "too large to compute in reasonable time"-error, it's easiest to just explicitly work only with floats in these circumstances.
至少这对幂运算有效,因为 print(10 ** 10 ** 10.0)
已经抛出了 OverflowError
。
At least this works with exponentiation since print(10**10**10.0)
already throws the OverflowError
.
另一种选择是使用 signal
之类的东西来限制执行时间那段脚本。
The other option would be using something like the signal
to limit the execution time of that piece of your script.
推荐答案
答案在 OverflowError
:
异常OverflowError
exception OverflowError
在算术运算的结果太大而无法表示时引发。对于整数而言,这种情况不会发生(宁可引发MemoryError而不是放弃)。
Raised when the result of an arithmetic operation is too large to be represented. This cannot occur for integers (which would rather raise MemoryError than give up).
因此,解决方案是,我猜想:与浮动
数字。但是,文档的其余部分也说明了大多数浮点运算也未得到检查的事实……我知道一个事实,即太大的 exp(x)
会引发 OverflowError
。
So the solution is, I guess: explicitly work with float
numbers. However the rest of the documentation says something about most floating point operations not being checked either... I know for a fact that a too big exp(x)
will raise an OverflowError
.
编辑:为您解决该问题的解决方案可能是根据您自己引发Exception python执行一些您感兴趣的代码所花费的时间。我不是这样做的专家,但是您有几种可能的方式来做到这一点此处。
a solution to deal with that problem for you would probably be to raise an Exception yourself depending on the time it takes python to execute a bit of code you're interested in. I'm no expert in doing that, but you have a few possible ways of doing that here.
这篇关于Python:巨大幂运算陷入困境,但不会引发错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!