【问题标题】:python 2 division蟒蛇2师
【发布时间】:2012-01-02 22:03:19
【问题描述】:
#this works in python 3
def pi_sum(n):
    total, k = 0,1
    while k <= n:
        total, k = total +8 /(k *(k+2)), k + 4
    return total

#this is how i tried to fix it for python 2
def pi_sum2(n):
    total, k = 0,1
    while k <= n:
        total, k = float(total +8) /(k *(k+2)), k + 4
    return total

在 python 2 中:对于pi_sum2(1e6),我得到8.000032000112001e-12。这里有什么问题?

EDIT 上面我的第一个错误是将浮点数应用于总计和 8.. 我应该做的:

#this is how i tried to fix it for python 2
def pi_sum2(n):
    total, k = 0,1
    while k <= n:
        total, k = total + float(8) /(k *(k+2)), k + 4
    return total

【问题讨论】:

  • 不应该是float(total) + 8 / (k *(k+2))吗?
  • oops close,但我发现它实际上应该是 total + float(8)/(k*(k+2))

标签: python division python-2.x


【解决方案1】:

您需要将变量显式定义为浮点数以避免某些类型强制:

def pi_sum(n):
    total, k = 0.0, 1.0
    while k <= n:
        total, k = total + 8.0 /(k *(k+2)), k + 4
    return total

应该做的伎俩

【讨论】:

  • 这行得通,但我还编辑了语句以显示如何使用 float() 来完成
  • 您可以使用8.0 而不是通过函数查找来调用float(8)
  • total, k = 0.0, 1 应该足够了,因为只有 total 用作浮点数。
  • 此外,单独执行total += 8.0 /(k *(k+2))k += 4 会更易读。恕我直言。
猜你喜欢
  • 2017-08-18
  • 1970-01-01
  • 2010-10-27
  • 2010-10-21
  • 2016-05-28
  • 2014-08-01
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多