Advertisement
jukaukor

Chudnovsky_Pi_me.py

Jul 22nd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. # Chudnovsky algorithm for Pi
  2. # https://en.wikipedia.org/wiki/Chudnovsky_algorithm
  3. # Muutettu rivi 10 alkuperäisestä itse ymmärrettyyn muotoon (12*k+2)...
  4. # lisätty aika
  5. # Juhani Kaukoranta 23.7.2019 wikipedian avulla
  6. from decimal import Decimal as Dec, getcontext as gc
  7. import time
  8. def PI(maxK, prec, disp):
  9. gc().prec = prec
  10. M, L, X, S = 1, 13591409, 1, 13591409
  11. for k in range(0, maxK+1):
  12. M = (12*k+2)*(12*k+6)*(12*k+10) * M // (k+1)**3
  13. L += 545140134
  14. X *= -262537412640768000
  15. S += Dec(M * L) / X
  16. pi = 426880 * Dec(10005).sqrt() / S
  17. pi = Dec(str(pi)[:disp]) # drop few digits of precision for accuracy
  18. print("PI(maxK={} iterations, gc().prec={}, disp={} digits) =\n{}".format(maxK, prec, disp, pi))
  19. return pi
  20. digits = int(input("How many digits in Pi "))
  21. maxK = int(digits*70/1006)+1
  22. prec =digits+8
  23. disp = digits+1
  24. # defaults maxK=70,prec=1008,disp=1006 chosen to gain 1000+ digits within a few seconds
  25. time0 = time.perf_counter()
  26. Pi = PI(maxK,prec,digits)
  27. time1 = time.perf_counter()
  28. print("Aikaa kului laskentaan ja tulostukseen ",time1-time0," sekuntia")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement