【问题标题】:inf not convertible to a floatinf 不能转换为浮点数
【发布时间】:2014-11-23 21:47:56
【问题描述】:

由于某种原因,一段时间后我的代码出现了问题, OverflowError: cannot convert float infinity to integer。 我看不出有什么理由这样做,很少使用浮点数,也没有使用 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)

但是,将 1.5 替换为 12 可以。为什么?

【问题讨论】:

  • 我刚刚注意到代码有点自引用!

标签: python-2.7 floating-point overflowexception


【解决方案1】:

bugs * 1.5 是浮点运算,因为浮点操作数 (1.5) 可以转换回整数。注意 bugs * 2bugs * 1 是整数运算,因为整数操作数。

它总是以指数速度增长 (bugs = int(bugs * 1.5))。

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

bugs * 2(如上所述的整数运算)之所以有效,是因为没有“无穷大”的概念或整数溢出错误。 bugs * 1,当然,永远运行。但是,bugs * 2.0 会失败。

【讨论】:

  • “整数只是环绕”有点误导:在普通 Python 中没有整数环绕(在自动减少模 2 的幂的意义上)。 (当然,NumPy 是另一回事。)
  • 那么如果我想让它以 1.5 的速度增长,我该怎么办?
  • @tox123 我想说不要将其转换为 int。但我不能给出比这更好的建议了。我实际上并不了解python。我确信有一种方法可以打印小数点为 0 的浮点数;可能是"%.0f bugs in the code ...".
猜你喜欢
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多