Home > database >  When is a Python Overflow Error generated?
When is a Python Overflow Error generated?

Time:03-22

Why do the below three lines produce different output in python3, despite the values being equal?

>>> 10 ** 500
100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

>>>1E500
inf

>>>1E250 ** 2
---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-110-d71dbae32ab9> in <module>
----> 1 1E250**2

CodePudding user response:

They are not equal. The first is an integer, and Python allows integers to be infinitely large. (Well, virtually infinite.) The other two are floating point numbers, and the value is beyond the range of a double. The 1E500 value is a constant, and overflows in constants result in the inf pseudo-value. The final one is an arithmetic operation, and Python detects and throws overflows in arithmetic operations.

  • Related