4

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
4
  • I don't think there is a consistent limit really. x ** 2 gets an error, but x * x does not. Commented Mar 6, 2016 at 22:23
  • @zondo - Well, there's a consistent limit in the sense that there is a maximum value that an IEE754 float can represent. Commented Mar 6, 2016 at 22:23
  • I'm not clear about what the question is. Are you asking for the minimum x for which sys.float_info.max + x is inf? Commented Mar 6, 2016 at 22:24
  • @DSM yes, but I think there is no definitive value for that based on Jaco's answer. Commented Mar 6, 2016 at 23:09

2 Answers 2

7

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That is what I thought, just wanted to get a definitive answer.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.