python-2.7floating-pointoverflowexception

inf not convertible to a float


For some reason after a while my code raises, OverflowError: cannot convert float infinity to integer. I can't see any reason why it would do this, there is little use of floats and no use of the inf,

def bugsInCode(begin):
    bugs = begin
    while bugs != 0:
        print "%s bugs in the code, %s bugs\ntake one down patch it around, %s bugs in the code!" % (bugs, bugs, int(bugs * 1.5))
        bugs = int(bugs * 1.5)

However replacing 1.5 with a 1 or a 2 works. Why?


Solution

  • bugs * 1.5 is a floating-point operation because of the floating-point operand (1.5), which you convert back to an integer. Note bugs * 2 and bugs * 1 are integer operations, because of the integer operands.

    It is always increasing, at an exponential rate (bugs = int(bugs * 1.5)).

    Eventually bugs will be an integer large enough such that bugs * 1.5 will exceed the maximum allowable value of a floating-point number, and thus will be "infinity". Then you try to convert that back to an integer, hence the error message, which is accurate.

    bugs * 2 (integer operation as mentioned) works because there is no concept of "infinity" or an overflow error for integers. bugs * 1, of course, just runs forever. bugs * 2.0, however, would fail.