2014-11-23 91 views
0

因为某些原因,我的代码提高后, OverflowError: cannot convert float infinity to integer。 我看不出有任何理由为什么它会做到这一点,很少有使用花车,没有使用INF的,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) 

但是有12作品代替1.5。为什么?

+0

我刚刚注意到代码有点自引用! – tox123 2014-11-23 21:48:35

回答

3

bugs * 1.5是一个浮点操作,因为浮点操作数(1.5),您将其转换回整数。注意bugs * 2bugs * 1是整数操作,因为整数操作数。

它一直在以指数速度增长(bugs = int(bugs * 1.5))。

最终bugs将是一个足够大的整数,因此bugs * 1.5将超过浮点数的最大允许值,因此将是“无穷大”。然后,您尝试将其转换回整数,因此错误消息是准确的。

bugs * 2(上述整数运算)的工作原理是因为没有“无限”概念或整数溢出错误。当然,这只是永远运行。然而,bugs * 2.0会失败。

+1

“整数只是环绕”有点让人误解:在纯Python中没有整数环绕(自动还原模的意思是某些2的幂)。 (当然,NumPy是另一回事。) – 2014-11-24 08:54:16

+0

所以如果我想让它以1.5的速度增长,我该怎么办? – tox123 2015-07-11 22:08:42

+0

@ tox123我会说不要将它转换为int。但我不能给出比这更好的建议。我其实不知道python。我确信有一种方法可以打印一个小数点后0位的浮点数;可能''%.0f代码中的错误......“'。 – 2015-07-14 05:50:47