How to calculate the value of pi using numerical approximations
The value of pi used in everyday calculations is as follows:
This value is only accurate up to the first four decimal points but gets the job done in everyday calculations. Since pi is irrational, its exact value, in decimal points, cannot be calculated. However, various numerical approximation methods improve accuracy and allow us to calculate the value up to tens of thousands of decimal places.
Gregory-Leibniz series
One of the simplest and oldest methods to calculate the value of pi is by using the Gregory-Leibniz series:
The only downside of using this series is that it requires the addition of several terms to get the value of pi accurate up to a few decimal places. Let’s translate this into code.
Code
n = 1pi = 0for i in range(1000000):if i % 2 == 0:pi += (1 / n)else:pi -= (1 / n)n += 2pi *= 4print(pi)
Explanation
Lines 1–2: Variables are created to store the value of
nandpi.Line 4: This is a
forloop that runs 1,000,000 times.Lines 5–6: The
i%2 == 0condition checks if the value ofiis even, i.e., if it is an even iteration of theforloop. It then adds1/nto the value of pi.Lines 7–8: If it's an odd iteration, we subtract
1/nfrom the value of pi.Line 9: We increment the value of
nby2for the calculation of the next term in the series.Line 11: We multiply the value of pi by
4to get the final result.Line 13: We display the value to the console.
Result
By running the code above, which adds the first million terms, we get the value of pi only accurate until the fifth decimal place. We can experiment with the number of iterations of the for loop and see how that value affects the accuracy of pi.
Note: If an execution timed out error occurs, try decreasing that value. Also note how increasing the value increases the time it takes to get the final result.
Ramanujan-Sato series
This is one of the more complicated series used to calculate the value of pi. Using this method, the value of pi can be accurately calculated up to a significant number of decimal places by using just the first few values. Here's how we write it:
Example
from math import factorial, sqrtpi_sum = 0for i in range(2):pi_sum += (factorial(4*i) * (26390*i + 1103)) / ((factorial(i) ** 4) * 396 ** (4*i))pi_sum *= (2*sqrt(2) / (99**2))pi = 1/pi_sumprint(pi)
Explanation
Line 1: We import the
factorialand square root functions from themathmodule.Line 3: We set the initial value of
pi_sumto0.Line 5: Here, a
forloop that runs two times.Line 6: This is the summation part of the Ramanujan-Sato Series formula.
Lines 8–9: These are the remaining calculations of the series to get the final value of pi.
Line 11: We print the final value of pi to the console.
Result
We can see that the for loop runs twice and produces a correct output that is accurate up to 15 decimal places. We can also change the number of loops to get a more (or less) accurate result.
Free Resources