To actually solve the problem, consider the following:
The fraction portion of the sum is:
-1/3+1/5-1/7+1/9 ...
What is the pattern here? Well, first the sign obviously alternates every number. Next, the denumerator starts at 3
and then adds 2
to it every iteration. This, when combined with the initial value of 1
leads us to the mathematical sum that is represented on the wiki page,
Sum(-1^n/(2n+1))
How to express this in code?
Well, in 99% of programming languages, if you are trying to express a sum, which is a formula that is based on some input number (n), and then added to itself with the value calculated at (n+1), you should think for loop
. in python, we can express that sum as so:
def approximate_pi(iterations):
sum = 0
for n in range(iterations):
sum += (-1)**n/(2*n+1)
return sum*4
This will, given a finite number of iterations, calculate an approximation of the value of π. The bigger iterarions
, the more accurate the result will be, at the cost of increased run time.
Python, however, has some shortcuts that make this even easier. The first is the built in function sum
, which returns the result of adding together the numbers in a list. The next is a list comprehension
, which produces a list from some input arguments. This simplifies our original function to the following:
approximate_pi(iterations):
return 4*sum([(-1)**n/(2*n+1) for n in range(iterations)])
This is doing basically the same series of operations, just in a way that's more efficient for python (for loops are expensive i n python) and that actually looks closer to the original pure mathematical notation.