tomiyama
tomiyama

Reputation: 45

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?

Upvotes: 1

Views: 159

Answers (3)

printf
printf

Reputation: 335

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).

Upvotes: 2

vikingosegundo
vikingosegundo

Reputation: 52237

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.

Upvotes: 0

dev55555
dev55555

Reputation: 437

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

Upvotes: 0

Related Questions