Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exhausting floating point precision in a (seemingly) infinite loop

I've got the following Python script:

x = 300000000.0
while (x < x + x):
    x = x + x
    print "exec: " + str(x)
print "terminated" + str(x)

This seemingly infinite loop, terminates pretty quickly if x is a floating point number. But if i change x to 300000000 instead, it gets into an infinite loop (runs longer than a minute in my test).

I think this is to do with the fact that it's exhausting the precision of a floating point number that can be represented in memory. Can someone provide a more detailed explanation why this is?

like image 635
Joe Tam Avatar asked Nov 30 '22 14:11

Joe Tam


2 Answers

  • When you initialize x to 300000000, integer math is used throughout the program.
  • When you initialize x to 300000000.0, floating-point math is used instead.

In Python, integers can grow arbitrarily large. (More accurately, they're limited by the available memory.) This means that the integer version of your program takes a very long time to terminate.

The largest float is about 1.8e308. It takes about 1000 iterations of the floating-point version of the loop to exceed that value, at which point x gets set to positive infinity, and the program terminates.

like image 88
NPE Avatar answered Apr 08 '23 09:04

NPE


This is because a floating-point overflow occurs. In that case, as per IEEE754, x will adopt the value positive infinity, which is by definition not less than anything else:

>>> x = float("inf")
>>> x
inf
>>> x + x
inf
>>> x < x + x
False
like image 31
Niklas B. Avatar answered Apr 08 '23 07:04

Niklas B.