bbp_pi.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. '''
  2. This implementation is a heavily modified fixed point implementation of
  3. BBP_formula for calculating the nth position of pi. The original hosted
  4. at: https://web.archive.org/web/20151116045029/http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python)
  5. # Permission is hereby granted, free of charge, to any person obtaining
  6. # a copy of this software and associated documentation files (the
  7. # "Software"), to deal in the Software without restriction, including
  8. # without limitation the rights to use, copy, modify, merge, publish,
  9. # distribute, sub-license, and/or sell copies of the Software, and to
  10. # permit persons to whom the Software is furnished to do so, subject to
  11. # the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be
  14. # included in all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  17. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  18. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  19. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  20. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  21. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  22. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  23. Modifications:
  24. 1.Once the nth digit and desired number of digits is selected, the
  25. number of digits of working precision is calculated to ensure that
  26. the hexadecimal digits returned are accurate. This is calculated as
  27. int(math.log(start + prec)/math.log(16) + prec + 3)
  28. --------------------------------------- --------
  29. / /
  30. number of hex digits additional digits
  31. This was checked by the following code which completed without
  32. errors (and dig are the digits included in the test_bbp.py file):
  33. for i in range(0,1000):
  34. for j in range(1,1000):
  35. a, b = pi_hex_digits(i, j), dig[i:i+j]
  36. if a != b:
  37. print('%s\n%s'%(a,b))
  38. Deceasing the additional digits by 1 generated errors, so '3' is
  39. the smallest additional precision needed to calculate the above
  40. loop without errors. The following trailing 10 digits were also
  41. checked to be accurate (and the times were slightly faster with
  42. some of the constant modifications that were made):
  43. >> from time import time
  44. >> t=time();pi_hex_digits(10**2-10 + 1, 10), time()-t
  45. ('e90c6cc0ac', 0.0)
  46. >> t=time();pi_hex_digits(10**4-10 + 1, 10), time()-t
  47. ('26aab49ec6', 0.17100000381469727)
  48. >> t=time();pi_hex_digits(10**5-10 + 1, 10), time()-t
  49. ('a22673c1a5', 4.7109999656677246)
  50. >> t=time();pi_hex_digits(10**6-10 + 1, 10), time()-t
  51. ('9ffd342362', 59.985999822616577)
  52. >> t=time();pi_hex_digits(10**7-10 + 1, 10), time()-t
  53. ('c1a42e06a1', 689.51800012588501)
  54. 2. The while loop to evaluate whether the series has converged quits
  55. when the addition amount `dt` has dropped to zero.
  56. 3. the formatting string to convert the decimal to hexadecimal is
  57. calculated for the given precision.
  58. 4. pi_hex_digits(n) changed to have coefficient to the formula in an
  59. array (perhaps just a matter of preference).
  60. '''
  61. import math
  62. from sympy.utilities.misc import as_int
  63. def _series(j, n, prec=14):
  64. # Left sum from the bbp algorithm
  65. s = 0
  66. D = _dn(n, prec)
  67. D4 = 4 * D
  68. k = 0
  69. d = 8 * k + j
  70. for k in range(n + 1):
  71. s += (pow(16, n - k, d) << D4) // d
  72. d += 8
  73. # Right sum iterates to infinity for full precision, but we
  74. # stop at the point where one iteration is beyond the precision
  75. # specified.
  76. t = 0
  77. k = n + 1
  78. e = 4*(D + n - k)
  79. d = 8 * k + j
  80. while True:
  81. dt = (1 << e) // d
  82. if not dt:
  83. break
  84. t += dt
  85. # k += 1
  86. e -= 4
  87. d += 8
  88. total = s + t
  89. return total
  90. def pi_hex_digits(n, prec=14):
  91. """Returns a string containing ``prec`` (default 14) digits
  92. starting at the nth digit of pi in hex. Counting of digits
  93. starts at 0 and the decimal is not counted, so for n = 0 the
  94. returned value starts with 3; n = 1 corresponds to the first
  95. digit past the decimal point (which in hex is 2).
  96. Examples
  97. ========
  98. >>> from sympy.ntheory.bbp_pi import pi_hex_digits
  99. >>> pi_hex_digits(0)
  100. '3243f6a8885a30'
  101. >>> pi_hex_digits(0, 3)
  102. '324'
  103. References
  104. ==========
  105. .. [1] http://www.numberworld.org/digits/Pi/
  106. """
  107. n, prec = as_int(n), as_int(prec)
  108. if n < 0:
  109. raise ValueError('n cannot be negative')
  110. if prec == 0:
  111. return ''
  112. # main of implementation arrays holding formulae coefficients
  113. n -= 1
  114. a = [4, 2, 1, 1]
  115. j = [1, 4, 5, 6]
  116. #formulae
  117. D = _dn(n, prec)
  118. x = + (a[0]*_series(j[0], n, prec)
  119. - a[1]*_series(j[1], n, prec)
  120. - a[2]*_series(j[2], n, prec)
  121. - a[3]*_series(j[3], n, prec)) & (16**D - 1)
  122. s = ("%0" + "%ix" % prec) % (x // 16**(D - prec))
  123. return s
  124. def _dn(n, prec):
  125. # controller for n dependence on precision
  126. # n = starting digit index
  127. # prec = the number of total digits to compute
  128. n += 1 # because we subtract 1 for _series
  129. return int(math.log(n + prec)/math.log(16) + prec + 3)