python - 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?
解决方案
在使用整数进行数值计算时,python不限于机器特定的数字,例如“int32”,因此“2147483647”这样的数字对它没有多大意义。相反,它使用“大整数”库,原则上,只要有足够的内存,它就可以表达任何大数。当面对诸如9**9**9
python 之类的计算时,试图准确地执行它,产生准确的结果,无论它有多大。对于这个特定的计算,它只需要很多时间(和内存,大概在内部 python 正在尝试根据需要分配越来越多的内存)。
推荐阅读
- javascript - 修改自动检测用户名和密码以在 Chrome 上保存密码建议
- java - 如何检测声明的exe在java中是否可见
- r - dplyr `left_join()` 不适用于作为 LHS 变量的字符对象
- ampl - 在ampl 中定义距离矩阵的函数。不断收到“我未定义”
- twitter-bootstrap - Bootstrap 年历 - 工作示例
- web-services - 微软语音 api 错误请求
- angularjs - ui-router 中的 AngularJS 组件/范围问题
- c# - 实体框架 6 BulkInsert 从客户端 SQL SERVER 2012 Express 接收到无效的列长度
- java - 导航栏打开时 MainActivity 仍然可以点击
- maven - 为多个依赖项指定相同的版本?