I was looking at the output from the code below. When I increment 1 to the maximum value of float, the output seems to be what I would expect, but when I do x=x*1.5, then I see inf as the output which I would assume is the float overflow. My question is, at what upper limit does it go from expected output to inf?
x=sys.float_info.max
x=x+1
x
The Python float does not have sufficient precision to store the + 1
for sys.float_info.max
, so the operations is effectively equivalent to adding zero. The below comparison actually returns True
:
print sys.float_info.max+1==sys.float_info.max
Only when you start adding numbers that are large enough to result in a change in the IEE754 binary representation of that float, you will get inf
, for example:
x+0.00000000000000001E308
returns inf
on my machine (Windows 64bit)
I am not having enough reputation to comment under the excellent answer given by Alex, but I think that it may mislead people coming here with different question on their mind, that is looking for the limit when incrementing stops to work as usually (i.e. stops actually incrementing), which is actually much much lower.
On my machine with current Python sys.float_info.max
is 1.7976931348623157e+308
When testing with the following code:
for a in range(300):
x = float("1.0e"+str(a))
if x != x+1:
print(x)
it turns out that incrementing stops working for numbers exceeding roughly 1e+15
, because of the limited range of the significand.
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