I wrote this code to calculate pi, I'm trying to calculate 2 million digits within at least a minute. This has proven to be really difficult and I can't find any way to further improve this code.
As of now this code can consistently calculate 100,000 digits in around 16 seconds. I've written it based off of the Wikipedia article: Wikipedia's article
My code:
from mpmath import mp, mpf, sqrt
from math import ceil
from time import time
print("Chudnovsky algorithm")
# THE FUNCTION
def chudnovsky(digits):
mp.dps = digits + 2 # extra precision
C = mpf(426880) * sqrt(10005)
L = mpf(13591409)
M = mpf(1)
X = mpf(1)
K = mpf(-6)
a1 = mpf(0)
for q in range(ceil(digits / 14.182)):
a1 += (M * L) / X
L += 545140134
X *= -262537412640768000
K += 12
M *= (K**3 - 16*K) / (q+1)**3
result = str(C * a1 ** -1)[:digits + 1] # cuts off extra potentially inaccurate digits
mp.dps = 10
return result
# GET USER INPUT
while True: # loops until an integer is entered
try:
user_input = int(input("\nHow many digits?: "))
break # this only get executed if the user types a valid integer
except ValueError: # if the user types in something that cant be interpreted as an integer
print("Enter an integer")
start = time()
print()
print(chudnovsky(user_input))
print()
print(f"Elapsed time: [{time() - start}s]")
Are there any inaccuracies in my code or is this as good as it gets?
I would recommend @Nick Craig-Wood methods to calculate Chudnovsky's Algorithm.
he has explained thoroughly and the timings are present for comparison.
https://www.craig-wood.com/nick/articles/pi-chudnovsky/
A code snippet from the website:
other methods are much faster that are mentioned on the site.
https://www.craig-wood.com/nick/articles/pi-chudnovsky/