简体   繁体   中英

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?

When doing numerical calculations with integers, python is not limited to machine-specific numbers such as "int32", and therefore a number such as "2147483647" does not mean much to it. Instead, it uses a "big integer" library, which can, in principle, express any large number, provided there is enough memory for it. When facing a computation such as 9**9**9 python tries to perform it exactly , producing the exact result, however big it may be. For this particular calculation it just takes a lot of time (and memory, presumably internally python is trying to allocate more and more memory as needed).

the num 9**9**9 is very big to caculated
you can wait untill it will return a result
it can take much long time

Why does my Python freeze when I do an overflow calculation?

because no overflow occurred and python hasn't given up. Python will extend the precision until either the calculation succeeds or the machine runs out of memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM