Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python float overflow, what happens when float overflows?

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
like image 213
user2997606 Avatar asked Sep 14 '25 20:09

user2997606


2 Answers

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)

like image 182
Alex Avatar answered Sep 16 '25 11:09

Alex


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.

like image 35
JJZ Avatar answered Sep 16 '25 10:09

JJZ