|
1 | | -def bailey_borwein_plouffe(digit_position: int, precision: int = 1000) -> str: |
| 1 | +""" |
| 2 | +Bailey-Borwein-Plouffe (BBP) Formula |
| 3 | +====================================== |
| 4 | +The BBP formula is a spigot algorithm for computing the nth binary digit |
| 5 | +of pi (pi) WITHOUT computing all preceding digits. It was discovered in 1995 |
| 6 | +by David Bailey, Peter Borwein, and Simon Plouffe. |
| 7 | +
|
| 8 | +The formula is: |
| 9 | + pi = Sum (1/16^k) * (4/(8k+1) - 2/(8k+4) - 1/(8k+5) - 1/(8k+6)) |
| 10 | + k=0 to infinity |
| 11 | +
|
| 12 | +This makes it possible to extract any single hexadecimal digit of pi directly. |
| 13 | +
|
| 14 | +References: |
| 15 | + - https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula |
| 16 | + - https://www.experimentalmath.info/bbp-codes/bbp-alg.pdf |
| 17 | + - Bailey, D. H., Borwein, P. B., & Plouffe, S. (1997). "On the Rapid |
| 18 | + Computation of Various Polylogarithmic Constants." Mathematics of |
| 19 | + Computation, 66(218), 903-913. |
| 20 | +""" |
| 21 | + |
| 22 | + |
| 23 | +def _modular_pow(base: int, exp: int, mod: int) -> float: |
| 24 | + """ |
| 25 | + Compute (base^exp) % mod using fast modular exponentiation, |
| 26 | + then return the fractional part when divided by mod. |
| 27 | +
|
| 28 | + This is a helper for the BBP digit-extraction algorithm. |
| 29 | +
|
| 30 | + Args: |
| 31 | + base: The base of the exponentiation. |
| 32 | + exp: The exponent (non-negative integer). |
| 33 | + mod: The modulus (positive integer). |
| 34 | +
|
| 35 | + Returns: |
| 36 | + The fractional part of (base^exp mod mod) / mod as a float. |
| 37 | +
|
| 38 | + Examples: |
| 39 | + >>> abs(_modular_pow(16, 0, 1) - 0.0) < 1e-10 |
| 40 | + True |
| 41 | + >>> 0.0 <= _modular_pow(16, 5, 7) < 1.0 |
| 42 | + True |
| 43 | + """ |
| 44 | + if mod == 1: |
| 45 | + return 0.0 |
| 46 | + |
| 47 | + result = 1 |
| 48 | + base = base % mod |
| 49 | + while exp > 0: |
| 50 | + if exp % 2 == 1: |
| 51 | + result = (result * base) % mod |
| 52 | + exp //= 2 |
| 53 | + base = (base * base) % mod |
| 54 | + |
| 55 | + return result / mod |
| 56 | + |
| 57 | + |
| 58 | +def _series(j: int, n: int) -> float: |
| 59 | + """ |
| 60 | + Compute the partial series used in the BBP formula: |
| 61 | + S_j(n) = Sum_{k=0}^{n} 16^(n-k) / (8k + j) (mod 1) |
| 62 | + + Sum_{k=n+1}^{inf} 16^(n-k) / (8k + j) |
| 63 | +
|
| 64 | + Args: |
| 65 | + j: The denominator offset (1, 4, 5, or 6 for the standard BBP formula). |
| 66 | + n: The 0-based index of the hexadecimal digit of pi to extract. |
| 67 | +
|
| 68 | + Returns: |
| 69 | + The fractional part of the series sum. |
| 70 | +
|
| 71 | + Examples: |
| 72 | + >>> 0.0 <= _series(1, 0) < 1.0 |
| 73 | + True |
| 74 | + >>> 0.0 <= _series(4, 10) < 1.0 |
| 75 | + True |
| 76 | + """ |
| 77 | + # Left sum: k = 0 to n (uses modular exponentiation) |
| 78 | + partial_sum = 0.0 |
| 79 | + for k in range(n + 1): |
| 80 | + denom = 8 * k + j |
| 81 | + partial_sum += _modular_pow(16, n - k, denom) |
| 82 | + partial_sum %= 1.0 |
| 83 | + |
| 84 | + # Right sum: k = n+1 to inf (geometrically decreasing, truncate when tiny) |
| 85 | + k = n + 1 |
| 86 | + while True: |
| 87 | + term = (16.0 ** (n - k)) / (8 * k + j) |
| 88 | + if term < 1e-15: |
| 89 | + break |
| 90 | + partial_sum += term |
| 91 | + partial_sum %= 1.0 |
| 92 | + k += 1 |
| 93 | + |
| 94 | + return partial_sum |
| 95 | + |
| 96 | + |
| 97 | +def bbp_pi_hex_digit(n: int) -> str: |
2 | 98 | """ |
3 | | - Implement a popular pi-digit-extraction algorithm known as the |
4 | | - Bailey-Borwein-Plouffe (BBP) formula to calculate the nth hex digit of pi. |
5 | | - Wikipedia page: |
6 | | - https://en.wikipedia.org/wiki/Bailey%E2%80%93Borwein%E2%80%93Plouffe_formula |
7 | | - @param digit_position: a positive integer representing the position of the digit to |
8 | | - extract. |
9 | | - The digit immediately after the decimal point is located at position 1. |
10 | | - @param precision: number of terms in the second summation to calculate. |
11 | | - A higher number reduces the chance of an error but increases the runtime. |
12 | | - @return: a hexadecimal digit representing the digit at the nth position |
13 | | - in pi's decimal expansion. |
14 | | -
|
15 | | - >>> "".join(bailey_borwein_plouffe(i) for i in range(1, 11)) |
16 | | - '243f6a8885' |
17 | | - >>> bailey_borwein_plouffe(5, 10000) |
18 | | - '6' |
19 | | - >>> bailey_borwein_plouffe(-10) |
20 | | - Traceback (most recent call last): |
21 | | - ... |
22 | | - ValueError: Digit position must be a positive integer |
23 | | - >>> bailey_borwein_plouffe(0) |
24 | | - Traceback (most recent call last): |
25 | | - ... |
26 | | - ValueError: Digit position must be a positive integer |
27 | | - >>> bailey_borwein_plouffe(1.7) |
28 | | - Traceback (most recent call last): |
29 | | - ... |
30 | | - ValueError: Digit position must be a positive integer |
31 | | - >>> bailey_borwein_plouffe(2, -10) |
32 | | - Traceback (most recent call last): |
33 | | - ... |
34 | | - ValueError: Precision must be a nonnegative integer |
35 | | - >>> bailey_borwein_plouffe(2, 1.6) |
36 | | - Traceback (most recent call last): |
37 | | - ... |
38 | | - ValueError: Precision must be a nonnegative integer |
| 99 | + Compute the nth fractional hexadecimal digit of pi (0-indexed) using the |
| 100 | + Bailey-Borwein-Plouffe (BBP) formula. |
| 101 | +
|
| 102 | + The BBP formula allows extracting ANY hexadecimal digit of pi directly, |
| 103 | + without calculating all prior digits. This is a spigot algorithm. |
| 104 | +
|
| 105 | + Pi in hexadecimal is 3.243F6A8885A308D3..., so this function returns |
| 106 | + the fractional digits: index 0 -> '2', index 1 -> '4', index 2 -> '3', etc. |
| 107 | +
|
| 108 | + Args: |
| 109 | + n: The 0-based position of the fractional hexadecimal digit to extract. |
| 110 | + n=0 gives '2' (first fractional digit of 3.243F6A8885A308D3...) |
| 111 | + n=1 gives '4' |
| 112 | + n=2 gives '3' |
| 113 | +
|
| 114 | + Returns: |
| 115 | + A single uppercase hexadecimal character (0-9, A-F). |
| 116 | +
|
| 117 | + Raises: |
| 118 | + ValueError: If n is negative. |
| 119 | +
|
| 120 | + Examples: |
| 121 | + >>> bbp_pi_hex_digit(0) |
| 122 | + '2' |
| 123 | + >>> bbp_pi_hex_digit(1) |
| 124 | + '4' |
| 125 | + >>> bbp_pi_hex_digit(2) |
| 126 | + '3' |
| 127 | + >>> bbp_pi_hex_digit(3) |
| 128 | + 'F' |
| 129 | + >>> bbp_pi_hex_digit(4) |
| 130 | + '6' |
| 131 | + >>> bbp_pi_hex_digit(5) |
| 132 | + 'A' |
| 133 | + >>> bbp_pi_hex_digit(10) |
| 134 | + 'A' |
| 135 | + >>> bbp_pi_hex_digit(-1) |
| 136 | + Traceback (most recent call last): |
| 137 | + ... |
| 138 | + ValueError: n must be a non-negative integer, got -1 |
39 | 139 | """ |
40 | | - if (not isinstance(digit_position, int)) or (digit_position <= 0): |
41 | | - raise ValueError("Digit position must be a positive integer") |
42 | | - if (not isinstance(precision, int)) or (precision < 0): |
43 | | - raise ValueError("Precision must be a nonnegative integer") |
44 | | - |
45 | | - # compute an approximation of (16 ** (n - 1)) * pi whose fractional part is mostly |
46 | | - # accurate |
47 | | - sum_result = ( |
48 | | - 4 * _subsum(digit_position, 1, precision) |
49 | | - - 2 * _subsum(digit_position, 4, precision) |
50 | | - - _subsum(digit_position, 5, precision) |
51 | | - - _subsum(digit_position, 6, precision) |
52 | | - ) |
53 | | - |
54 | | - # return the first hex digit of the fractional part of the result |
55 | | - return hex(int((sum_result % 1) * 16))[2:] |
56 | | - |
57 | | - |
58 | | -def _subsum( |
59 | | - digit_pos_to_extract: int, denominator_addend: int, precision: int |
60 | | -) -> float: |
61 | | - # only care about first digit of fractional part; don't need decimal |
| 140 | + if n < 0: |
| 141 | + msg = f"n must be a non-negative integer, got {n}" |
| 142 | + raise ValueError(msg) |
| 143 | + |
| 144 | + # pi in hex: 3.243F6A8885A308D3... |
| 145 | + # The BBP formula computes the fractional hex digit at position n |
| 146 | + x = 4.0 * _series(1, n) - 2.0 * _series(4, n) - _series(5, n) - _series(6, n) |
| 147 | + |
| 148 | + # Normalize to [0, 1) and extract first hex digit |
| 149 | + x = x % 1.0 |
| 150 | + digit_value = int(x * 16) |
| 151 | + return format(digit_value, "X") |
| 152 | + |
| 153 | + |
| 154 | +def pi_hex_string(num_digits: int) -> str: |
62 | 155 | """ |
63 | | - Private helper function to implement the summation |
64 | | - functionality. |
65 | | - @param digit_pos_to_extract: digit position to extract |
66 | | - @param denominator_addend: added to denominator of fractions in the formula |
67 | | - @param precision: same as precision in main function |
68 | | - @return: floating-point number whose integer part is not important |
| 156 | + Generate the first `num_digits` hexadecimal digits of pi using the BBP formula. |
| 157 | +
|
| 158 | + Note: Each call to bbp_pi_hex_digit is O(n log n), so this function |
| 159 | + is O(n^2 log n) overall. It is intended for educational use, not |
| 160 | + high-performance computation. |
| 161 | +
|
| 162 | + Args: |
| 163 | + num_digits: The number of hexadecimal digits to compute (must be > 0). |
| 164 | +
|
| 165 | + Returns: |
| 166 | + A string of `num_digits` uppercase hexadecimal characters. |
| 167 | +
|
| 168 | + Raises: |
| 169 | + ValueError: If num_digits is not a positive integer. |
| 170 | +
|
| 171 | + Examples: |
| 172 | + >>> pi_hex_string(1) |
| 173 | + '2' |
| 174 | + >>> pi_hex_string(5) |
| 175 | + '243F6' |
| 176 | + >>> pi_hex_string(10) |
| 177 | + '243F6A8885' |
| 178 | + >>> pi_hex_string(0) |
| 179 | + Traceback (most recent call last): |
| 180 | + ... |
| 181 | + ValueError: num_digits must be a positive integer, got 0 |
69 | 182 | """ |
70 | | - total = 0.0 |
71 | | - for sum_index in range(digit_pos_to_extract + precision): |
72 | | - denominator = 8 * sum_index + denominator_addend |
73 | | - if sum_index < digit_pos_to_extract: |
74 | | - # if the exponential term is an integer and we mod it by the denominator |
75 | | - # before dividing, only the integer part of the sum will change; |
76 | | - # the fractional part will not |
77 | | - exponential_term = pow( |
78 | | - 16, digit_pos_to_extract - 1 - sum_index, denominator |
79 | | - ) |
80 | | - else: |
81 | | - exponential_term = pow(16, digit_pos_to_extract - 1 - sum_index) |
82 | | - total += exponential_term / denominator |
83 | | - return total |
| 183 | + if num_digits <= 0: |
| 184 | + msg = f"num_digits must be a positive integer, got {num_digits}" |
| 185 | + raise ValueError(msg) |
| 186 | + |
| 187 | + return "".join(bbp_pi_hex_digit(i) for i in range(num_digits)) |
84 | 188 |
|
85 | 189 |
|
86 | 190 | if __name__ == "__main__": |
87 | 191 | import doctest |
88 | 192 |
|
89 | 193 | doctest.testmod() |
| 194 | + |
| 195 | + print("Bailey-Borwein-Plouffe (BBP) Formula Demo") |
| 196 | + print("=" * 45) |
| 197 | + print("pi in hexadecimal: 3.243F6A8885A308D3...") |
| 198 | + print("BBP extracts the fractional hex digits: 2, 4, 3, F, 6, A, ...") |
| 199 | + print() |
| 200 | + for pos in range(15): |
| 201 | + digit = bbp_pi_hex_digit(pos) |
| 202 | + print(f" Fractional hex digit at position {pos:2d}: {digit}") |
| 203 | + |
| 204 | + print() |
| 205 | + print(f"First 15 fractional hex digits of pi: {pi_hex_string(15)}") |
| 206 | + print("Expected: 243F6A8885A308D") |
0 commit comments