【发布时间】: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