用书中的级数计算pi
我又在努力提高我的编程水平,这次是学习Python,但遇到了瓶颈。我已经尝试了很久想弄明白为什么这个代码不工作,如果能有人帮帮我,那真是太好了。我有一些说明作为注释,但系列数据没法复制到文本里,不过在维基百科上可以找到,链接是 http://en.wikipedia.org/wiki/Pi#Estimating_.CF.80
#19. Write a program that approximates the value of pi by summing the terms of this series:
#The program should prompt the user for n, the number of terms to sum
# and then output the sum of the first n terms of this series.
def pi() :
n = 0.0
p = input()
for i in range(-3,p*4,4):
n = n + 4.0 / i - 4.0 / ( i + 2)
print n
当我输入1000000时,结果是5.80825432026;这个值变化不大。总之,有人能帮我吗?现在我实在想不到其他办法了。
4 个回答
0
一般来说,在进行浮点数运算时,先把最小的数加起来是个好主意,这样可以减少四舍五入时的误差。因此,我建议对John Machin的答案做一个小小的修改。
>>> def pi(n):
... tot = 0.0
... for i in reversed(xrange(1, n * 4, 4)):
... tot += 4.0 / i - 4.0 / (i + 2)
... return tot
1
为什么你的范围从-3开始?你的函数用 range(1,p*4,4)
也能正常工作,尽管 p
不是项的数量。
3
起点不对。使用合理的变量名(问题中提到的是n,所以就用n,不要用p)。检查上限……要得到n个项,你需要进行(n // 2)次迭代,而你现在大约进行了n次迭代。
>>> def pi(n):
... tot = 0.0
... for i in xrange(1, n * 4, 4):
... tot += 4.0 / i - 4.0 / (i + 2)
... return tot
...
>>> pi(1000)
3.1410926536210386
>>> pi(10000)
3.1415426535898203
>>> pi(100000)
3.141587653589818
>>>