tags:

views:

288

answers:

2

The German mathematician Gottfried Leibniz developed the following method to approximate the value of pi: pi/4 = 1- 1/3 + 1/5 - 1/7 + 1/9 - 1/11 ...

Write a program that allows the user to specify the number of iterations used in this approximation and that displays the resulting value for pi.

+20  A: 
import itertools as it

def pi(n):
    coefficients = it.cycle((1, -1))
    divisors = it.islice(it.count(1), 0, n, 2)
    return 4*sum(c * 1.0/d for c, d in it.izip(coefficients, divisors))

Should do the trick. Thank you for donating this portion of your education to a simple high school drop out.

aaronasterling
+1 for sarcasm ` `
abhin4v
multiply the sum by 4?
MattH
You left out the part about prompting the user for the number of terms, and how to call this pi function whatzis, and how to print out the answer. And how to install Python. And how to turn on my computer....
Paul McGuire
@MattH. fixed. Thanks.
aaronasterling
@MattH - or rename function to pi_over_4
Paul McGuire
@Paul: Aaron is just delivering to spec.
MattH
Probably the most useful part of this answer is that nobody who has to ask how to implement this algorithm would *ever* come up with this solution--it shows how to do it, but in a way that the OP won't be able to understand and could never explain when asked by the teacher. *it's a trap*
Glenn Maynard
Thanks for the anonymous downvote. I was ten upvotes over my repcap but because of the downvote, I got 2 rep for this answer.
aaronasterling
+1  A: 

There is another implementation here:

http://snippets.dzone.com/posts/show/5433

rafaelcidade