Advertisement
jukaukor

BorweinPlouffeHexPi_numba.py

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