开发者

Calculating pi using a series in my book

I'm trying (yet again) to get better at programming, this time in python, and I've hit a roadblock. I've been trying to figure out why this doesn't work for a while now, so if I could have some help that would be really, really great. I have the instructions as a comment, but the series wouldn't copy to text, it's on wikipedia though as 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 

When I say 1000000, it gives me 5.80825432026; that value doesn't change much. Anyway, can someo开发者_开发技巧ne help me please? At this point I have nothing else I can think of.


Wrong starting point. Use sensible variable names (question says n, so use n, not p). Check upper bound ... to get n terms you need to do (n // 2) iterations, you are doing approx n iterations.

>>> 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
>>>


Why does your range start at -3? Your function works fine with range(1,p*4,4) although p is not the number of terms.


In general for floating point math it's a good idea to add up the smallest terms first to minimize rounding errors, so I'd recommend this tiny modification of John Machin's answer

>>> 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


Based on the wikipedia page cited, I would go for this implementation:

def pi(p) :
    def powers():
        while True:
            yield 1.0
            yield -1.0
    return 4.0 * sum(p / i for i, p in zip(range(1,2*p+1,2), powers()))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜