#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
。这有什么不对?
编辑高于我的第一个错误是将浮动应用于总数和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
答案 0 :(得分: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
应该做的伎俩