ENG | New iterative method of computing Pi, Python implementation.
Python implementation of method Pi computation by Arnab Priya Saha and Aninda Sinha.
ENG | New iterative method of computing Pi, Python implementation.
Let’s try it to rewrite the newly discovered formula below to Python and terminate it when difference from the last value drops below epsilon. That does not mean that we reached certain number of digits or precision.
It’s not the fastest way to calculate pi, many articles or youtube videos are just comparing it to very early and very slow methods.
\[\pi = 4 + \sum_{n=1}^{\infty} \frac{1}{n!} \left(\frac{1}{n+\lambda} - \frac{4}{2n+1}\right) \left(\frac{(2n+1)^2}{4(n+\lambda)} - n\right)_{n-1}\]Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python3
import math
def calculate_pi(lambda_val, epsilon):
pi = 4
n = 1
prev_pi = 0
factorial = n
while abs(pi - prev_pi) >= epsilon:
term1 = 1.0 / factorial
term2 = 1.0 / (n + lambda_val) - 4 / (2*n + 1)
term3 = ((2*n + 1)**2) / (4 * (n + lambda_val)) - n
pochhammer = 1
for i in range(n-1):
pochhammer *= (term3 + i)
prev_pi = pi
pi += term1 * term2 * pochhammer
print(f"| {n:9d} | {pi:18.14f} |")
n += 1
factorial = factorial * n
return pi, n - 1
# Set parameters
lambda_val = 42
epsilon = 1e-14
# Print header
print("| Iteration | Value |")
print("|----------:|--------------------|")
# Calculate pi
result, iterations = calculate_pi(lambda_val, epsilon)
# Print footer
print("\n\n")
print(f"Approximated value of pi: {result}")
print(f"Value of math.pi: {math.pi}")
print(f"Number of iterations: {iterations}")
print(f"Difference from math.pi: {abs(result - math.pi)}")
Output of the program is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| Iteration | Value |
|----------:|--------------------|
| 1 | 2.68992248062016 |
| 2 | 3.41199117896726 |
| 3 | 2.98059015669278 |
| 4 | 3.23092257836903 |
| 5 | 3.09759277217522 |
| 6 | 3.15982559407870 |
| 7 | 3.13577365685025 |
| 8 | 3.14271607338608 |
| 9 | 3.14164498636753 |
| 10 | 3.14148195723408 |
| 11 | 3.14161399411790 |
| 12 | 3.14160032529400 |
| 13 | 3.14158896731957 |
| 14 | 3.14159216583788 |
| 15 | 3.14159315334142 |
| 16 | 3.14159269869881 |
| 17 | 3.14159258717138 |
| 18 | 3.14159264455809 |
| 19 | 3.14159266216640 |
| 20 | 3.14159265589384 |
| 21 | 3.14159265268522 |
| 22 | 3.14159265307537 |
| 23 | 3.14159265361480 |
| 24 | 3.14159265367637 |
| 25 | 3.14159265361029 |
| 26 | 3.14159265358214 |
| 27 | 3.14159265358379 |
| 28 | 3.14159265358887 |
| 29 | 3.14159265359046 |
| 30 | 3.14159265359024 |
| 31 | 3.14159265358987 |
| 32 | 3.14159265358975 |
| 33 | 3.14159265358976 |
Approximated value of pi: 3.1415926535897585
Value of math.pi: 3.141592653589793
Number of iterations: 33
Difference from math.pi: 3.4638958368304884e-14
Reference
This post is licensed under CC BY 4.0 by the author.