Advertisement
jukaukor

BourweinPlouffePi_nth.py

Aug 2nd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. # Python program with numba's njit calculates only nth hex
  2. # Computing nth hex digit of Pi with BBP formula.
  3. # Bailey-Borwein-Plouffe_formula for Pi
  4. # Uses numba compiler & njit directive for speed
  5. # Juhani Kaukoranta 2.8.2018
  6. # muokattu 4.8.2019 poistamalla 10 hex numeron tulostus
  7.  
  8. import math
  9. import time
  10. #from numba import njit
  11.  
  12. # Convert Pi to Hex-strings
  13. # (float number's decimals to hex digits)
  14.  
  15. def convHex(x) :
  16. hx = "0123456789ABCDEF"
  17. y = math.fabs(x)
  18. chx =''
  19. for i in range(0,16):
  20. y = 16.0 * (y - math.floor(y))
  21. chx += hx[int(y)]
  22. return chx
  23.  
  24. # Compute Modular Exponentiation
  25. @njit
  26. def compModExp(b, e, m):
  27. if (e == 0):
  28. return 1
  29. ans = compModExp(b, e // 2, m)
  30. ans = (ans * ans) % m
  31. if ((e % 2) == 1):
  32. ans = (ans * b) % m
  33. return ans
  34.  
  35. # Compute Sums
  36. @njit
  37. def Sums(j):
  38. s = 0.0
  39. # t // Each term of right summation
  40. # r // Denominator
  41. # k // Loop index
  42. # EPS = Loop-exit accuration of the right summation
  43.  
  44. EPS = 1.0e-17
  45. # Left Sum (0 ... n)
  46. k = 0
  47. for k in range(0,n+1):
  48. r = 8 * k + j
  49. t = compModExp(16, n - k, r)
  50. t /= r
  51. s += t - int(t)
  52. s -= int(s)
  53.  
  54. #Right sum (n + 1 ...)
  55. k = n+1
  56. while (1) :
  57. r = 8 * k + j
  58. t = 16**(n - k)
  59. t /= r
  60. if (t < EPS):
  61. break
  62. s += t
  63. s -= int(s)
  64. k += 1
  65.  
  66. return s # left + right
  67.  
  68. # paaohjelma kysyy halutun hex-muotoisen desimaalin järjestysnumeroa
  69. # tulostaa sen ja laskennassa käytetyn desimaalimuotoisen fraktion
  70.  
  71. n = int(input("kuinka mones Piin desimaali halutaan laskea?"))
  72. print("**** PI Computation ( hex digit number: ", n,", waiting..." )
  73. # Compute PI
  74. n = n - 1
  75. t0 = time.perf_counter() # time start
  76. pi = 4 * Sums(1) - 2 * Sums(4) - Sums(5) - Sums(6)
  77. pi = pi - int(pi) + 1
  78. pi_hex = convHex(pi)
  79. print("Hex digit: ", pi_hex[0])
  80. print("FRACTION : ", pi)
  81. t1 = time.perf_counter() # time end
  82. print("Aikaa kului ", t1 - t0," sekuntia")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement