Exhausting Floating Point Precision In A (seemingly) Infinite Loop
Solution 1:
- When you initialize
x
to300000000
, integer math is used throughout the program. - When you initialize
x
to300000000.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.
Solution 2:
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
Solution 3:
x
doubles after each step. A finite number x
is never equal to 2 * x
. But once you exceed the maximum exponent of your floating point type, the doubling turns x
to +infinity
. And +infinity = 2*+infinity
. So the loop terminates at that point.
Post a Comment for "Exhausting Floating Point Precision In A (seemingly) Infinite Loop"