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.
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.
n = 1 pi = 0 for i in range(1000000): if i % 2 == 0: pi += (1 / n) else: pi -= (1 / n) n += 2 pi *= 4 print(pi)
forloop that runs 1,000,000 times.
i%2 == 0condition checks if the value of
iis even, i.e., if it is an even iteration of the
forloop. It then adds
1/nto the value of pi.
1/nfrom the value of pi.
2for the calculation of the next term in the series.
4to get the final 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.
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:
from math import factorial, sqrt pi_sum = 0 for 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_sum print(pi)
factorialand square root functions from the
forloop that runs two times.
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.
View all Courses