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)
n
and pi
.for
loop that runs 1,000,000 times.i%2 == 0
condition checks if the value of i
is even, i.e., if it is an even iteration of the for
loop. It then adds 1/n
to the value of pi.1/n
from the value of pi.n
by 2
for the calculation of the next term in the series.4
to 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)
factorial
and square root functions from the math
module.pi_sum
to 0
.for
loop 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.
RELATED TAGS
CONTRIBUTOR
View all Courses