jukaukor

Chudnovsky_Pi.py

Mar 14th, 2022 (edited)
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. # Chudnovsky algorithm for Pi
  2. from decimal import Decimal as Dec, getcontext as gc
  3. import time
  4. def PI(maxK=70, prec=1008, disp=1007): # parameter defaults chosen to gain 1000+ digits within a few seconds
  5. gc().prec = prec
  6. K, M, L, X, S = 6, 1, 13591409, 1, 13591409
  7. for k in range(1, maxK+1):
  8. M = (K**3 - 16*K) * M // k**3
  9. L += 545140134
  10. X *= -262537412640768000
  11. S += Dec(M * L) / X
  12. K += 12
  13. pi = 426880 * Dec(10005).sqrt() / S
  14. pi = Dec(str(pi)[:disp]) # drop few digits of precision for accuracy
  15. print("PI(maxK={} iterations, gc().prec={}, disp={} digits) =\n{}".format(maxK, prec, disp, pi))
  16. return pi
  17. time0 = time.perf_counter()
  18. Pi = PI()
  19. time1 = time.perf_counter()
  20. print("computing and printing time ",time1-time0)
  21. print("\nFor greater precision and more digits (takes a few extra seconds) - Try")
  22. print("Pi = PI(317,4501,4500)")
  23. print("Pi = PI(353,5022,5020)")
Add Comment
Please, Sign In to add comment