>>> 1e100000000
inf
>>> 1000000 ... [400 zeroes snipped] ... 000000
1000000 ... [400 zeroes snipped] ... 000000
>>> 1000000 ... [400 zeroes snipped] ... 000000.0
inf
Why does Python decide that large floats are infinite? If the representation can't represent that value, I would expect it to give an error, like this does:
>>> 10.0 ** 1000000000000000000000000000000000000000000000000000000
OverflowError: (34, 'Numerical result out of range')
Why is the first case silent if the second case complains?
Because you tried to create a floating point number that is larger that the largest value representable in a floating point value.
See the sys.float_info named tuple; sys.float_info.max is the largest value representable in such values. Python floats, unlike Python integers, have an upper limit determined by your OS and hardware platform, integers are limited by your available memory.
On my Mac, that maximum value is:
>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308
So a 1 with 308 zeros is representable, but a 2 with that many zeros is not:
>>> float('1' + '0' * 308)
1e+308
>>> float('2' + '0' * 308)
inf
Floats are limited because floating point arithmetic is typically handled by the floating point unit on your CPU, and Python's float type is limited to what that piece of hardware can handle.
Defining a float literal is a different operation from applying arithmetic to a floating point value; the first is determined at compile time, the latter is determined at runtime. A literal could only produce a SyntaxError exception, while at runtime you can throw other exceptions. But throwing a syntax error for a float literal that on other platforms could still be valid is not really an option, so instead of an exception you get float('inf') instead.
The Python specification for float literals only declares that the permitted range is implementation dependent:
The allowed range of floating point literals is implementation-dependent.
There is a point where calculations too return float('inf') because once you have reached infinity calculations are easy (most cases just give you a form of infinity back), but close to infinity you get overflows instead. The float exponentiation implementation simply uses the C pow() function, and the exception is thrown when that function reports an overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With