0

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?

tox123
  • 318
  • 9
  • 21

1 Answers1

3

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.

Jason C
  • 38,729
  • 14
  • 126
  • 182
  • 1
    "the integers just wrap around" is a bit misleading: there's no integer wraparound (in the sense of automatic reduction modulo some power of 2) in plain Python. (NumPy is a different matter, of course.) – Mark Dickinson Nov 24 '14 at 08:54
  • So if I wanted it to grow at a rate of 1.5 what should I do? – tox123 Jul 11 '15 at 22:08
  • @tox123 I'd say don't convert it to an int. But I can't give better advice than that. I don't actually know python. I'm sure there's a way to print a float with 0 decimal places; probably `"%.0f bugs in the code ..."`. – Jason C Jul 14 '15 at 05:50