Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Chudnovsky algorithm for Pi
- from decimal import Decimal as Dec, getcontext as gc
- import time
- def PI(maxK=70, prec=1008, disp=1007): # parameter defaults chosen to gain 1000+ digits within a few seconds
- gc().prec = prec
- K, M, L, X, S = 6, 1, 13591409, 1, 13591409
- for k in range(1, maxK+1):
- M = (K**3 - 16*K) * M // k**3
- L += 545140134
- X *= -262537412640768000
- S += Dec(M * L) / X
- K += 12
- pi = 426880 * Dec(10005).sqrt() / S
- pi = Dec(str(pi)[:disp]) # drop few digits of precision for accuracy
- print("PI(maxK={} iterations, gc().prec={}, disp={} digits) =\n{}".format(maxK, prec, disp, pi))
- return pi
- time0 = time.perf_counter()
- Pi = PI()
- time1 = time.perf_counter()
- print("computing and printing time ",time1-time0)
- print("\nFor greater precision and more digits (takes a few extra seconds) - Try")
- print("Pi = PI(317,4501,4500)")
- print("Pi = PI(353,5022,5020)")
Add Comment
Please, Sign In to add comment