ceexp 0.3.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ceexp/__init__.py +12 -0
- ceexp/benchmark.py +309 -0
- ceexp/constant.py +139 -0
- ceexp/expansions.py +165 -0
- ceexp/residue.py +121 -0
- ceexp/series.py +95 -0
- ceexp/verify.py +53 -0
- ceexp-0.3.2.dist-info/METADATA +108 -0
- ceexp-0.3.2.dist-info/RECORD +14 -0
- ceexp-0.3.2.dist-info/WHEEL +5 -0
- ceexp-0.3.2.dist-info/entry_points.txt +2 -0
- ceexp-0.3.2.dist-info/licenses/LICENSE +21 -0
- ceexp-0.3.2.dist-info/licenses/LICENSE-docs.md +10 -0
- ceexp-0.3.2.dist-info/top_level.txt +1 -0
ceexp/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""ceexp: expansions, block-wise unit-fraction series and residues of the Copeland-Erdos constant."""
|
|
2
|
+
from .constant import (concatenation_digits, copeland_erdos_digits, cumulative_digit_counts,
|
|
3
|
+
digits_in_base, first_primes, int_from_digits, int_to_digits, primes_up_to,
|
|
4
|
+
unlimited_int_digits)
|
|
5
|
+
from .expansions import (certified, certified_interval, continued_fraction, engel,
|
|
6
|
+
greedy_egyptian, luroth, pierce)
|
|
7
|
+
from .residue import (legendre, multiplicative_order, residues, rounding_identity_holds,
|
|
8
|
+
ten_is_square_mod)
|
|
9
|
+
from .series import (BLOCK_RULES, CARRY_MODES, blocks, blockwise_series, nico_leon_series,
|
|
10
|
+
prime_blockwise_series)
|
|
11
|
+
|
|
12
|
+
__version__ = "0.3.2"
|
ceexp/benchmark.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""Precision-failure benchmark for Engel, Pierce, Luroth, and continued fractions.
|
|
2
|
+
|
|
3
|
+
Compares uncertified arithmetic engines (IEEE-754 float64, fixed-precision
|
|
4
|
+
Decimal, mpmath.mpf when installed, and uncertified integer truncation) against
|
|
5
|
+
interval-certified ground truth from ``ceexp.certified_interval``, reporting
|
|
6
|
+
the exact 1-based term index where silent numerical divergence occurs, along
|
|
7
|
+
with wall-clock time and peak memory.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import decimal
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
import tracemalloc
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Callable
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
import mpmath
|
|
23
|
+
except ImportError: # pragma: no cover - optional dependency
|
|
24
|
+
mpmath = None
|
|
25
|
+
|
|
26
|
+
from .constant import copeland_erdos_digits, digits_in_base
|
|
27
|
+
from .expansions import (
|
|
28
|
+
certified_interval,
|
|
29
|
+
continued_fraction,
|
|
30
|
+
engel,
|
|
31
|
+
luroth,
|
|
32
|
+
pierce,
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
BASE_GUARD_DIGITS = 64
|
|
36
|
+
EXPANSIONS: dict[str, Callable[..., list[int]]] = {
|
|
37
|
+
"engel": engel,
|
|
38
|
+
"pierce": pierce,
|
|
39
|
+
"luroth": luroth,
|
|
40
|
+
"continued_fraction": continued_fraction,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _champernowne_digits(n_digits: int, base: int) -> list[int]:
|
|
45
|
+
out: list[int] = []
|
|
46
|
+
k = 1
|
|
47
|
+
while len(out) < n_digits:
|
|
48
|
+
out.extend(digits_in_base(k, base))
|
|
49
|
+
k += 1
|
|
50
|
+
return out[:n_digits]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _base_digits_to_decimal_str(digits: list[int], base: int, n_digits: int) -> str:
|
|
54
|
+
sys.set_int_max_str_digits(max(10000, n_digits + 100))
|
|
55
|
+
|
|
56
|
+
def to_int(seq: list[int], cache: dict[int, int]) -> int:
|
|
57
|
+
n = len(seq)
|
|
58
|
+
if n <= 64:
|
|
59
|
+
acc = 0
|
|
60
|
+
for d in seq:
|
|
61
|
+
acc = acc * base + d
|
|
62
|
+
return acc
|
|
63
|
+
mid = n // 2
|
|
64
|
+
rlen = n - mid
|
|
65
|
+
if rlen not in cache:
|
|
66
|
+
cache[rlen] = base**rlen
|
|
67
|
+
return to_int(seq[:mid], cache) * cache[rlen] + to_int(seq[mid:], cache)
|
|
68
|
+
|
|
69
|
+
num = to_int(digits, {})
|
|
70
|
+
scaled = (num * (10**n_digits)) // (base ** len(digits))
|
|
71
|
+
return str(scaled).zfill(n_digits)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def run_float64(digits: str, mode: str, max_terms: int) -> list[int]:
|
|
75
|
+
"""Uncertified IEEE-754 float64 expansion."""
|
|
76
|
+
x = float(f"0.{digits[:25]}")
|
|
77
|
+
terms: list[int] = []
|
|
78
|
+
for _ in range(max_terms):
|
|
79
|
+
if mode == "continued_fraction":
|
|
80
|
+
if not math.isfinite(x):
|
|
81
|
+
break
|
|
82
|
+
q = math.floor(x)
|
|
83
|
+
terms.append(q)
|
|
84
|
+
r = x - q
|
|
85
|
+
if r <= 0.0:
|
|
86
|
+
break
|
|
87
|
+
x = 1.0 / r
|
|
88
|
+
continue
|
|
89
|
+
if x <= 0.0 or not math.isfinite(x):
|
|
90
|
+
break
|
|
91
|
+
a = math.floor(1.0 / x) if mode == "pierce" else math.ceil(1.0 / x)
|
|
92
|
+
if a <= 0:
|
|
93
|
+
break
|
|
94
|
+
terms.append(a)
|
|
95
|
+
if mode == "engel":
|
|
96
|
+
x = a * x - 1.0
|
|
97
|
+
elif mode == "pierce":
|
|
98
|
+
x = 1.0 - a * x
|
|
99
|
+
else: # luroth
|
|
100
|
+
x = (a - 1) * (a * x - 1.0)
|
|
101
|
+
return terms
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def run_decimal(digits: str, mode: str, prec: int, max_terms: int) -> list[int]:
|
|
105
|
+
"""Uncertified fixed-precision Decimal expansion."""
|
|
106
|
+
ctx = decimal.Context(prec=prec)
|
|
107
|
+
x = ctx.create_decimal(f"0.{digits[:prec + 10]}")
|
|
108
|
+
one = decimal.Decimal(1)
|
|
109
|
+
terms: list[int] = []
|
|
110
|
+
for _ in range(max_terms):
|
|
111
|
+
if mode == "continued_fraction":
|
|
112
|
+
q = int(x.to_integral_value(rounding=decimal.ROUND_FLOOR))
|
|
113
|
+
terms.append(q)
|
|
114
|
+
r = ctx.subtract(x, decimal.Decimal(q))
|
|
115
|
+
if r <= 0:
|
|
116
|
+
break
|
|
117
|
+
x = ctx.divide(one, r)
|
|
118
|
+
continue
|
|
119
|
+
if x <= 0:
|
|
120
|
+
break
|
|
121
|
+
inv = ctx.divide(one, x)
|
|
122
|
+
rounding = decimal.ROUND_FLOOR if mode == "pierce" else decimal.ROUND_CEILING
|
|
123
|
+
a = int(inv.to_integral_value(rounding=rounding))
|
|
124
|
+
if a <= 0:
|
|
125
|
+
break
|
|
126
|
+
terms.append(a)
|
|
127
|
+
prod = ctx.multiply(decimal.Decimal(a), x)
|
|
128
|
+
if mode == "engel":
|
|
129
|
+
x = ctx.subtract(prod, one)
|
|
130
|
+
elif mode == "pierce":
|
|
131
|
+
x = ctx.subtract(one, prod)
|
|
132
|
+
else: # luroth
|
|
133
|
+
x = ctx.multiply(decimal.Decimal(a - 1), ctx.subtract(prod, one))
|
|
134
|
+
return terms
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def run_mpmath(digits: str, mode: str, dps: int, max_terms: int) -> list[int]:
|
|
138
|
+
"""Uncertified fixed-precision mpmath.mpf expansion."""
|
|
139
|
+
if mpmath is None:
|
|
140
|
+
return []
|
|
141
|
+
with mpmath.workdps(dps):
|
|
142
|
+
x = mpmath.mpf(f"0.{digits[:dps + 10]}")
|
|
143
|
+
terms: list[int] = []
|
|
144
|
+
for _ in range(max_terms):
|
|
145
|
+
if mode == "continued_fraction":
|
|
146
|
+
q = int(mpmath.floor(x))
|
|
147
|
+
terms.append(q)
|
|
148
|
+
r = x - q
|
|
149
|
+
if r <= 0:
|
|
150
|
+
break
|
|
151
|
+
x = 1 / r
|
|
152
|
+
continue
|
|
153
|
+
if x <= 0:
|
|
154
|
+
break
|
|
155
|
+
inv = 1 / x
|
|
156
|
+
a = int(mpmath.floor(inv) if mode == "pierce" else mpmath.ceil(inv))
|
|
157
|
+
if a <= 0:
|
|
158
|
+
break
|
|
159
|
+
terms.append(a)
|
|
160
|
+
if mode == "engel":
|
|
161
|
+
x = a * x - 1
|
|
162
|
+
elif mode == "pierce":
|
|
163
|
+
x = 1 - a * x
|
|
164
|
+
else: # luroth
|
|
165
|
+
x = (a - 1) * (a * x - 1)
|
|
166
|
+
return terms
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def run_uncertified_truncation(
|
|
170
|
+
digits: str, exp_fn: Callable[..., list[int]], trunc_digits: int, max_terms: int
|
|
171
|
+
) -> list[int]:
|
|
172
|
+
"""Uncertified rational expansion on a truncated decimal prefix."""
|
|
173
|
+
prefix = digits[:trunc_digits]
|
|
174
|
+
return exp_fn(int(prefix), 10 ** len(prefix), max_terms=max_terms, guard=0)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def first_divergence_index(truth: list[int], candidate: list[int]) -> int | None:
|
|
178
|
+
"""Return the 1-based index of the first mismatch, or None if prefix matches."""
|
|
179
|
+
limit = min(len(truth), len(candidate))
|
|
180
|
+
for i in range(limit):
|
|
181
|
+
if truth[i] != candidate[i]:
|
|
182
|
+
return i + 1
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _measure(fn: Callable[[], list[int]]) -> tuple[list[int], float, float]:
|
|
187
|
+
"""Run `fn` and return (result, elapsed_ms, peak_kb)."""
|
|
188
|
+
tracemalloc.start()
|
|
189
|
+
ts = time.monotonic()
|
|
190
|
+
res = fn()
|
|
191
|
+
ms = round((time.monotonic() - ts) * 1000, 2)
|
|
192
|
+
_, peak = tracemalloc.get_traced_memory()
|
|
193
|
+
tracemalloc.stop()
|
|
194
|
+
return res, ms, round(peak / 1024, 1)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def build_benchmark_constants(n_digits: int) -> dict[str, str]:
|
|
198
|
+
"""Build standard stress-test constants at `n_digits` decimal precision."""
|
|
199
|
+
c_digits = "".join(str(d) for d in copeland_erdos_digits(n_digits))
|
|
200
|
+
ch10_digits = "".join(str(d) for d in _champernowne_digits(n_digits, 10))
|
|
201
|
+
n_hex = math.ceil(n_digits * math.log(10) / math.log(16)) + BASE_GUARD_DIGITS
|
|
202
|
+
ch16_digits = _base_digits_to_decimal_str(
|
|
203
|
+
_champernowne_digits(n_hex, 16), 16, n_digits
|
|
204
|
+
)
|
|
205
|
+
return {
|
|
206
|
+
"copeland_erdos_10": c_digits,
|
|
207
|
+
"champernowne_10": ch10_digits,
|
|
208
|
+
"champernowne_16": ch16_digits,
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def run_benchmark(
|
|
213
|
+
n_digits: int = 50_000,
|
|
214
|
+
decimal_precs: tuple[int, ...] = (50, 200, 1000),
|
|
215
|
+
trunc_digits: tuple[int, ...] = (500, 2000),
|
|
216
|
+
modes: tuple[str, ...] = ("engel", "pierce", "luroth", "continued_fraction"),
|
|
217
|
+
) -> dict[str, object]:
|
|
218
|
+
"""Benchmark uncertified engines against interval-certified ground truth."""
|
|
219
|
+
constants = build_benchmark_constants(n_digits)
|
|
220
|
+
report: dict[str, object] = {
|
|
221
|
+
"n_digits": n_digits,
|
|
222
|
+
"mpmath_version": getattr(mpmath, "__version__", None),
|
|
223
|
+
"cases": {},
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
for name, digits in constants.items():
|
|
227
|
+
case_entry: dict[str, object] = {}
|
|
228
|
+
for mode in modes:
|
|
229
|
+
exp_fn = EXPANSIONS[mode]
|
|
230
|
+
truth, cert_ms, cert_kb = _measure(lambda: certified_interval(exp_fn, digits))
|
|
231
|
+
max_terms = len(truth)
|
|
232
|
+
engines: dict[str, object] = {}
|
|
233
|
+
|
|
234
|
+
def record(label: str, fn: Callable[[], list[int]]) -> None:
|
|
235
|
+
cand, ms, kb = _measure(fn)
|
|
236
|
+
div_k = first_divergence_index(truth, cand)
|
|
237
|
+
entry: dict[str, object] = {
|
|
238
|
+
"terms_produced": len(cand),
|
|
239
|
+
"first_divergence_k": div_k,
|
|
240
|
+
"elapsed_ms": ms,
|
|
241
|
+
"peak_kb": kb,
|
|
242
|
+
}
|
|
243
|
+
if div_k is not None:
|
|
244
|
+
entry["truth_term"] = str(truth[div_k - 1])[:24]
|
|
245
|
+
entry["engine_term"] = str(cand[div_k - 1])[:24]
|
|
246
|
+
engines[label] = entry
|
|
247
|
+
|
|
248
|
+
record("float64", lambda: run_float64(digits, mode, max_terms))
|
|
249
|
+
for prec in decimal_precs:
|
|
250
|
+
record(
|
|
251
|
+
f"decimal_{prec}",
|
|
252
|
+
lambda p=prec: run_decimal(digits, mode, p, max_terms),
|
|
253
|
+
)
|
|
254
|
+
if mpmath is not None:
|
|
255
|
+
record(
|
|
256
|
+
f"mpmath_{prec}",
|
|
257
|
+
lambda p=prec: run_mpmath(digits, mode, p, max_terms),
|
|
258
|
+
)
|
|
259
|
+
for td in trunc_digits:
|
|
260
|
+
if td < n_digits:
|
|
261
|
+
record(
|
|
262
|
+
f"trunc_{td}",
|
|
263
|
+
lambda d=td: run_uncertified_truncation(
|
|
264
|
+
digits, exp_fn, d, max_terms
|
|
265
|
+
),
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
case_entry[mode] = {
|
|
269
|
+
"certified_terms": max_terms,
|
|
270
|
+
"certified_elapsed_ms": cert_ms,
|
|
271
|
+
"certified_peak_kb": cert_kb,
|
|
272
|
+
"engines": engines,
|
|
273
|
+
}
|
|
274
|
+
report["cases"][name] = case_entry
|
|
275
|
+
return report
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def main() -> None:
|
|
279
|
+
n_digits = int(sys.argv[1]) if len(sys.argv) > 1 else 50_000
|
|
280
|
+
report = run_benchmark(n_digits=n_digits)
|
|
281
|
+
|
|
282
|
+
repo_root = Path(__file__).resolve().parent.parent.parent
|
|
283
|
+
if (repo_root / "pyproject.toml").exists():
|
|
284
|
+
out_path = repo_root / "experiments" / "results" / "precision_benchmark.json"
|
|
285
|
+
else:
|
|
286
|
+
out_path = Path.cwd() / "precision_benchmark.json"
|
|
287
|
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
|
288
|
+
out_path.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
|
289
|
+
|
|
290
|
+
print(
|
|
291
|
+
f"Precision-failure benchmark (N={n_digits:,} digits, mpmath={report['mpmath_version']})"
|
|
292
|
+
)
|
|
293
|
+
for name, modes in report["cases"].items():
|
|
294
|
+
for mode, data in modes.items():
|
|
295
|
+
summary = ", ".join(
|
|
296
|
+
f"{eng}=k@{info['first_divergence_k']}"
|
|
297
|
+
if info["first_divergence_k"] is not None
|
|
298
|
+
else f"{eng}=ok({info['terms_produced']})"
|
|
299
|
+
for eng, info in data["engines"].items()
|
|
300
|
+
)
|
|
301
|
+
print(
|
|
302
|
+
f" {name:18s} [{mode:18s}] cert={data['certified_terms']:5d} "
|
|
303
|
+
f"({data['certified_elapsed_ms']:.0f}ms, {data['certified_peak_kb']:.0f}KB) -> {summary}"
|
|
304
|
+
)
|
|
305
|
+
print(f"Saved report to {out_path}")
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
if __name__ == "__main__":
|
|
309
|
+
main()
|
ceexp/constant.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Digits of the Copeland-Erdos constant and related prime-counting helpers.
|
|
2
|
+
|
|
3
|
+
The Copeland-Erdos constant is C = 0.2357111317192329..., obtained by concatenating
|
|
4
|
+
the primes in base 10 (OEIS A033308). Everything here uses exact integer arithmetic
|
|
5
|
+
without mutating global Python limits.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
import sys
|
|
11
|
+
import warnings
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from itertools import accumulate
|
|
14
|
+
|
|
15
|
+
# Stay strictly under Python 3.11+'s default 4300-digit int <-> str limit.
|
|
16
|
+
_STR_CHUNK = 2000
|
|
17
|
+
_SAFE_BIT_LEN = 13000 # 2^13000 < 10^3914 < 10^4300
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@contextmanager
|
|
21
|
+
def unlimited_int_digits():
|
|
22
|
+
"""Deprecated: mutates the process-global int <-> str limit (not thread-safe).
|
|
23
|
+
|
|
24
|
+
Prefer ``int_from_digits`` and ``int_to_digits``, which convert arbitrary-size
|
|
25
|
+
integers via divide-and-conquer without touching global state.
|
|
26
|
+
"""
|
|
27
|
+
warnings.warn(
|
|
28
|
+
"unlimited_int_digits mutates global Python state and is not thread-safe; "
|
|
29
|
+
"use int_from_digits/int_to_digits instead.",
|
|
30
|
+
DeprecationWarning,
|
|
31
|
+
stacklevel=2,
|
|
32
|
+
)
|
|
33
|
+
old = sys.get_int_max_str_digits()
|
|
34
|
+
sys.set_int_max_str_digits(0)
|
|
35
|
+
try:
|
|
36
|
+
yield
|
|
37
|
+
finally:
|
|
38
|
+
sys.set_int_max_str_digits(old)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _int_from_digits_dc(digits: str, pow10_cache: dict[int, int]) -> int:
|
|
42
|
+
n = len(digits)
|
|
43
|
+
if n <= _STR_CHUNK:
|
|
44
|
+
return int(digits)
|
|
45
|
+
mid = n // 2
|
|
46
|
+
right_len = n - mid
|
|
47
|
+
if right_len not in pow10_cache:
|
|
48
|
+
pow10_cache[right_len] = 10**right_len
|
|
49
|
+
return (
|
|
50
|
+
_int_from_digits_dc(digits[:mid], pow10_cache) * pow10_cache[right_len]
|
|
51
|
+
+ _int_from_digits_dc(digits[mid:], pow10_cache)
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def int_from_digits(digits: str) -> int:
|
|
56
|
+
"""Parse an arbitrary-length decimal string without mutating global limits."""
|
|
57
|
+
if not digits:
|
|
58
|
+
return 0
|
|
59
|
+
return _int_from_digits_dc(digits, {})
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _int_to_digits_dc(n: int, pow10_cache: dict[int, int]) -> str:
|
|
63
|
+
if n.bit_length() <= _SAFE_BIT_LEN:
|
|
64
|
+
return str(n)
|
|
65
|
+
approx_digits = int(n.bit_length() * 0.3010299956639812) + 1
|
|
66
|
+
half = max(_STR_CHUNK, approx_digits // 2)
|
|
67
|
+
if half not in pow10_cache:
|
|
68
|
+
pow10_cache[half] = 10**half
|
|
69
|
+
q, r = divmod(n, pow10_cache[half])
|
|
70
|
+
return _int_to_digits_dc(q, pow10_cache) + _int_to_digits_dc(r, pow10_cache).zfill(half)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def int_to_digits(n: int) -> str:
|
|
74
|
+
"""Convert an arbitrary-size non-negative int to decimal str without global state."""
|
|
75
|
+
if n < 0:
|
|
76
|
+
raise ValueError("int_to_digits expects a non-negative integer")
|
|
77
|
+
if n == 0:
|
|
78
|
+
return "0"
|
|
79
|
+
return _int_to_digits_dc(n, {})
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def primes_up_to(limit: int) -> list[int]:
|
|
83
|
+
"""All primes p <= limit (sieve of Eratosthenes)."""
|
|
84
|
+
if limit < 2:
|
|
85
|
+
return []
|
|
86
|
+
sieve = bytearray([1]) * (limit + 1)
|
|
87
|
+
sieve[0:2] = b"\x00\x00"
|
|
88
|
+
for i in range(2, int(limit**0.5) + 1):
|
|
89
|
+
if sieve[i]:
|
|
90
|
+
sieve[i * i :: i] = bytearray(len(range(i * i, limit + 1, i)))
|
|
91
|
+
return [i for i, flag in enumerate(sieve) if flag]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def first_primes(count: int) -> list[int]:
|
|
95
|
+
"""The first `count` primes, using the Rosser-Schoenfeld upper bound (single sieve)."""
|
|
96
|
+
if count <= 0:
|
|
97
|
+
return []
|
|
98
|
+
# Rosser-Schoenfeld (1962): p_n < n * (ln n + ln ln n) for all n >= 6.
|
|
99
|
+
limit = 15 if count < 6 else math.ceil(count * (math.log(count) + math.log(math.log(count)))) + 3
|
|
100
|
+
while True:
|
|
101
|
+
ps = primes_up_to(limit)
|
|
102
|
+
if len(ps) >= count:
|
|
103
|
+
return ps[:count]
|
|
104
|
+
limit *= 2
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def digits_in_base(n: int, base: int = 10) -> list[int]:
|
|
108
|
+
"""Digits of n >= 1 in the given base, most significant first."""
|
|
109
|
+
out = []
|
|
110
|
+
while n:
|
|
111
|
+
n, r = divmod(n, base)
|
|
112
|
+
out.append(r)
|
|
113
|
+
return out[::-1]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def concatenation_digits(n_digits: int, base: int = 10) -> list[int]:
|
|
117
|
+
"""First `n_digits` digits after the radix point of 0.(2)(3)(5)(7)(11)... in `base`."""
|
|
118
|
+
if n_digits <= 0:
|
|
119
|
+
return []
|
|
120
|
+
# Total base-b digits of primes <= X is ~ X / ln(base) by PNT.
|
|
121
|
+
limit = max(100, int(n_digits * math.log(base) * 1.15) + 100)
|
|
122
|
+
out: list[int] = []
|
|
123
|
+
while True:
|
|
124
|
+
out.clear()
|
|
125
|
+
for p in primes_up_to(limit):
|
|
126
|
+
out.extend(digits_in_base(p, base))
|
|
127
|
+
if len(out) >= n_digits:
|
|
128
|
+
return out[:n_digits]
|
|
129
|
+
limit *= 2
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def copeland_erdos_digits(n_digits: int) -> str:
|
|
133
|
+
"""First `n_digits` decimal digits of the Copeland-Erdos constant, as a string."""
|
|
134
|
+
return "".join(map(str, concatenation_digits(n_digits, 10)))
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def cumulative_digit_counts(primes: list[int], base: int = 10) -> list[int]:
|
|
138
|
+
"""d(n) = number of base-`base` digits in the concatenation of primes[0..n-1] (A068670 for base 10)."""
|
|
139
|
+
return list(accumulate(len(digits_in_base(p, base)) for p in primes))
|
ceexp/expansions.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Classical expansions of a positive real given to finite precision.
|
|
2
|
+
|
|
3
|
+
Every function takes the real as an exact rational n/d (typically d = 10^N for N known
|
|
4
|
+
digits) and returns only terms that the available precision certifies: a term is emitted
|
|
5
|
+
only while the digits it consumes stay below the precision budget minus `guard` digits.
|
|
6
|
+
Callers should still confirm terms by recomputing at a higher precision (see verify.py).
|
|
7
|
+
|
|
8
|
+
Definitions (x > 0):
|
|
9
|
+
Engel: x = 1/a1 + 1/(a1 a2) + 1/(a1 a2 a3) + ..., a_k = ceil(1/x_k), x_{k+1} = a_k x_k - 1
|
|
10
|
+
Pierce: x = 1/b1 - 1/(b1 b2) + 1/(b1 b2 b3) - ..., b_k = floor(1/x_k), x_{k+1} = 1 - b_k x_k
|
|
11
|
+
Greedy (Fibonacci-Sylvester) Egyptian fraction:
|
|
12
|
+
x = 1/g1 + 1/g2 + ..., g_k = ceil(1/x_k), x_{k+1} = x_k - 1/g_k
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import warnings
|
|
17
|
+
from math import log10
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
import gmpy2 # type: ignore[import-not-found]
|
|
21
|
+
except ImportError: # pragma: no cover - optional dependency
|
|
22
|
+
gmpy2 = None
|
|
23
|
+
|
|
24
|
+
from .constant import int_from_digits
|
|
25
|
+
|
|
26
|
+
LOG10_2 = 0.30102999566398120
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _digits(n: int) -> float:
|
|
30
|
+
"""Approximate log10(n) for a positive integer of any size."""
|
|
31
|
+
return n.bit_length() * LOG10_2
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def engel(n: int, d: int, max_terms: int = 10**6, guard: int = 40) -> list[int]:
|
|
35
|
+
budget = _digits(d) - guard
|
|
36
|
+
out, used = [], 0.0
|
|
37
|
+
for _ in range(max_terms):
|
|
38
|
+
if n <= 0:
|
|
39
|
+
break
|
|
40
|
+
a = -(-d // n)
|
|
41
|
+
used += _digits(a) if a > 1 else 0.0
|
|
42
|
+
if used > budget:
|
|
43
|
+
break
|
|
44
|
+
out.append(a)
|
|
45
|
+
n = n * a - d
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def pierce(n: int, d: int, max_terms: int = 10**6, guard: int = 40) -> list[int]:
|
|
50
|
+
if not 0 < n < d:
|
|
51
|
+
raise ValueError("Pierce expansion needs 0 < x < 1")
|
|
52
|
+
budget = _digits(d) - guard
|
|
53
|
+
out, used = [], 0.0
|
|
54
|
+
for _ in range(max_terms):
|
|
55
|
+
if n <= 0:
|
|
56
|
+
break
|
|
57
|
+
b = d // n
|
|
58
|
+
used += _digits(b) if b > 1 else LOG10_2
|
|
59
|
+
if used > budget:
|
|
60
|
+
break
|
|
61
|
+
out.append(b)
|
|
62
|
+
n = d - b * n
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def greedy_egyptian(n: int, d: int, max_terms: int = 64, guard: int = 40) -> list[int]:
|
|
67
|
+
budget = _digits(d) - guard
|
|
68
|
+
out = []
|
|
69
|
+
for _ in range(max_terms):
|
|
70
|
+
if n <= 0:
|
|
71
|
+
break
|
|
72
|
+
g = -(-d // n)
|
|
73
|
+
if 2 * _digits(g) > budget: # the remainder after 1/g is about 1/g^2
|
|
74
|
+
break
|
|
75
|
+
out.append(g)
|
|
76
|
+
n, d = n * g - d, d * g
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def common_prefix(a: list[int], b: list[int]) -> list[int]:
|
|
81
|
+
k = 0
|
|
82
|
+
while k < min(len(a), len(b)) and a[k] == b[k]:
|
|
83
|
+
k += 1
|
|
84
|
+
return a[:k]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def certified_interval(expansion, digits: str, **kw) -> list[int]:
|
|
88
|
+
"""Terms rigorously valid for every x in [L, U], L = 0.digits, U = L + 10^-N.
|
|
89
|
+
|
|
90
|
+
For the Engel, Pierce, greedy, Luroth, and continued-fraction maps the set of x
|
|
91
|
+
sharing their first k terms is an interval, and each map is continuous and monotone
|
|
92
|
+
on it, so if L and U share their first k terms, every x in [L, U] does. Uses
|
|
93
|
+
``gmpy2.mpz`` automatically when installed, falling back to Python ``int``.
|
|
94
|
+
"""
|
|
95
|
+
n_int = int_from_digits(digits)
|
|
96
|
+
if gmpy2 is not None:
|
|
97
|
+
n = gmpy2.mpz(n_int)
|
|
98
|
+
d = gmpy2.mpz(10) ** len(digits)
|
|
99
|
+
return [int(t) for t in common_prefix(expansion(n, d, **kw), expansion(n + 1, d, **kw))]
|
|
100
|
+
d = 10 ** len(digits)
|
|
101
|
+
return common_prefix(expansion(n_int, d, **kw), expansion(n_int + 1, d, **kw))
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def certified(expansion, digits: str, *, ratio: int = 2, **kw) -> list[int]:
|
|
105
|
+
"""Deprecated heuristic check: terms that agree when precision is cut by `ratio`.
|
|
106
|
+
|
|
107
|
+
Use ``certified_interval`` for a formal mathematical proof of every returned term.
|
|
108
|
+
"""
|
|
109
|
+
warnings.warn(
|
|
110
|
+
"certified() is a precision-halving heuristic; use certified_interval() for a "
|
|
111
|
+
"formal interval proof.",
|
|
112
|
+
DeprecationWarning,
|
|
113
|
+
stacklevel=2,
|
|
114
|
+
)
|
|
115
|
+
hi = expansion(int_from_digits(digits), 10 ** len(digits), **kw)
|
|
116
|
+
cut = len(digits) // ratio
|
|
117
|
+
lo = expansion(int_from_digits(digits[:cut]), 10**cut, **kw)
|
|
118
|
+
return common_prefix(lo, hi)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def luroth(n: int, d: int, max_terms: int = 10**6, guard: int = 40) -> list[int]:
|
|
122
|
+
"""Luroth expansion: a_k = ceil(1/x_k), x_{k+1} = (a_k - 1)(a_k x_k - 1)."""
|
|
123
|
+
budget = _digits(d) - guard
|
|
124
|
+
out, used = [], 0.0
|
|
125
|
+
for _ in range(max_terms):
|
|
126
|
+
if n <= 0:
|
|
127
|
+
break
|
|
128
|
+
a = -(-d // n)
|
|
129
|
+
used += _digits(a) + (_digits(a - 1) if a > 2 else 0.0)
|
|
130
|
+
if used > budget:
|
|
131
|
+
break
|
|
132
|
+
out.append(a)
|
|
133
|
+
n = (a - 1) * (a * n - d)
|
|
134
|
+
return out
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def continued_fraction(n: int, d: int, max_terms: int = 10**6, guard: int = 40) -> list[int]:
|
|
138
|
+
"""Regular continued fraction [a_0; a_1, ...] via Euclidean division."""
|
|
139
|
+
budget = _digits(d) - guard
|
|
140
|
+
out, used = [], 0.0
|
|
141
|
+
for _ in range(max_terms):
|
|
142
|
+
if d <= 0:
|
|
143
|
+
break
|
|
144
|
+
q, r = divmod(n, d)
|
|
145
|
+
used += (2.0 * _digits(q)) if q > 0 else 0.0
|
|
146
|
+
if used > budget:
|
|
147
|
+
break
|
|
148
|
+
out.append(q)
|
|
149
|
+
if r == 0:
|
|
150
|
+
break
|
|
151
|
+
n, d = d, r
|
|
152
|
+
return out
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
__all__ = [
|
|
156
|
+
"engel",
|
|
157
|
+
"pierce",
|
|
158
|
+
"greedy_egyptian",
|
|
159
|
+
"luroth",
|
|
160
|
+
"continued_fraction",
|
|
161
|
+
"certified",
|
|
162
|
+
"certified_interval",
|
|
163
|
+
"common_prefix",
|
|
164
|
+
"log10",
|
|
165
|
+
]
|
ceexp/residue.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""The prime-concatenation residue r_b(n) = b^{d_b(n)} mod p_n and its algebraic structure.
|
|
2
|
+
|
|
3
|
+
d_b(n) is the number of base-b digits in the concatenation of the first n primes, so for
|
|
4
|
+
b = 10, d(n) is the position of the last digit of p_n in the Copeland-Erdos constant
|
|
5
|
+
(A068670) and r(n) = 10^{d(n)} mod p_n is p_n times the fractional part of 10^{d(n)}/p_n.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
import random
|
|
11
|
+
|
|
12
|
+
from .constant import cumulative_digit_counts, first_primes
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def residues(n_terms: int, base: int = 10) -> tuple[list[int], list[int], list[int]]:
|
|
16
|
+
"""(primes, d_b(n), r_b(n)) for n = 1..n_terms."""
|
|
17
|
+
ps = first_primes(n_terms)
|
|
18
|
+
ds = cumulative_digit_counts(ps, base)
|
|
19
|
+
return ps, ds, [pow(base, d, p) for p, d in zip(ps, ds)]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def legendre(a: int, p: int) -> int:
|
|
23
|
+
"""Legendre symbol (a/p) for an odd prime p, by Euler's criterion."""
|
|
24
|
+
t = pow(a % p, (p - 1) // 2, p)
|
|
25
|
+
return -1 if t == p - 1 else t
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def ten_is_square_mod(p: int) -> bool:
|
|
29
|
+
"""(10/p) = +1 <=> p = +-1, +-3, +-9, +-13 (mod 40) (paper: quadratic character)."""
|
|
30
|
+
return p % 40 in (1, 3, 9, 13, 27, 31, 37, 39)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _is_prime_mr(n: int) -> bool:
|
|
34
|
+
"""Deterministic Miller-Rabin for 64-bit integers and strong probable prime beyond."""
|
|
35
|
+
if n < 2:
|
|
36
|
+
return False
|
|
37
|
+
for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
|
|
38
|
+
if n == p:
|
|
39
|
+
return True
|
|
40
|
+
if n % p == 0:
|
|
41
|
+
return False
|
|
42
|
+
d, s = n - 1, 0
|
|
43
|
+
while d % 2 == 0:
|
|
44
|
+
d //= 2
|
|
45
|
+
s += 1
|
|
46
|
+
for a in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
|
|
47
|
+
if a >= n:
|
|
48
|
+
continue
|
|
49
|
+
x = pow(a, d, n)
|
|
50
|
+
if x == 1 or x == n - 1:
|
|
51
|
+
continue
|
|
52
|
+
for _ in range(s - 1):
|
|
53
|
+
x = (x * x) % n
|
|
54
|
+
if x == n - 1:
|
|
55
|
+
break
|
|
56
|
+
else:
|
|
57
|
+
return False
|
|
58
|
+
return True
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _pollard_rho(n: int, rng: random.Random) -> int:
|
|
62
|
+
if n % 2 == 0:
|
|
63
|
+
return 2
|
|
64
|
+
while True:
|
|
65
|
+
c = rng.randrange(1, n)
|
|
66
|
+
x = rng.randrange(2, n)
|
|
67
|
+
y = x
|
|
68
|
+
d = 1
|
|
69
|
+
while d == 1:
|
|
70
|
+
x = (x * x + c) % n
|
|
71
|
+
y = (y * y + c) % n
|
|
72
|
+
y = (y * y + c) % n
|
|
73
|
+
d = math.gcd(abs(x - y), n)
|
|
74
|
+
if d != n:
|
|
75
|
+
return d
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _prime_factors(n: int) -> set[int]:
|
|
79
|
+
factors: set[int] = set()
|
|
80
|
+
for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
|
|
81
|
+
while n % p == 0:
|
|
82
|
+
factors.add(p)
|
|
83
|
+
n //= p
|
|
84
|
+
# Small trial division up to 10^4 before falling back to Pollard's rho.
|
|
85
|
+
q = 41
|
|
86
|
+
while q * q <= n and q <= 10_000:
|
|
87
|
+
while n % q == 0:
|
|
88
|
+
factors.add(q)
|
|
89
|
+
n //= q
|
|
90
|
+
q += 2
|
|
91
|
+
if n == 1:
|
|
92
|
+
return factors
|
|
93
|
+
rng = random.Random(0xC0FFEE)
|
|
94
|
+
stack = [n]
|
|
95
|
+
while stack:
|
|
96
|
+
x = stack.pop()
|
|
97
|
+
if x == 1:
|
|
98
|
+
continue
|
|
99
|
+
if _is_prime_mr(x):
|
|
100
|
+
factors.add(x)
|
|
101
|
+
continue
|
|
102
|
+
d = _pollard_rho(x, rng)
|
|
103
|
+
stack.append(d)
|
|
104
|
+
stack.append(x // d)
|
|
105
|
+
return factors
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def multiplicative_order(a: int, p: int) -> int:
|
|
109
|
+
"""Order of a modulo the prime p (a not divisible by p), using Pollard's rho."""
|
|
110
|
+
m = p - 1
|
|
111
|
+
for f in _prime_factors(m):
|
|
112
|
+
while m % f == 0 and pow(a, m // f, p) == 1:
|
|
113
|
+
m //= f
|
|
114
|
+
return m
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def rounding_identity_holds(p: int, d: int) -> bool:
|
|
118
|
+
"""10^d - round(10^d/p) * p equals the centred residue (paper: the residue is the rounding error)."""
|
|
119
|
+
r = pow(10, d, p)
|
|
120
|
+
a = (2 * 10**d + p) // (2 * p)
|
|
121
|
+
return 10**d - a * p == (r if 2 * r < p else r - p)
|
ceexp/series.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Block-wise unit-fraction series of the Copeland-Erdos constant and its variants.
|
|
2
|
+
|
|
3
|
+
Target: T_k = 0.B1 B2 ... Bk, where each block B_j is written with L_j digits in `base`.
|
|
4
|
+
With debt carry ("ceil"): a_k = ceil(1/(T_k - S_{k-1})), S_k = S_{k-1} + 1/a_k, E_k = T_k - S_k >= 0.
|
|
5
|
+
With signed carry ("signed"): a_k = round(1/|T_k - S_{k-1}|), S_k = S_{k-1} + sign/a_k.
|
|
6
|
+
Without carry ("none"): a_k = round(base^{d_k} / B_k), each block approximated on its own.
|
|
7
|
+
|
|
8
|
+
Block rules:
|
|
9
|
+
"prime" B_j = p_j (whole prime, one step per prime)
|
|
10
|
+
"digit" one step per digit of the concatenation (zero digits advance the position only)
|
|
11
|
+
"mod_base" B_j = p_j mod base (one digit per prime)
|
|
12
|
+
"digital_root" B_j = 1 + (p_j - 1) mod (base - 1)
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from fractions import Fraction
|
|
18
|
+
|
|
19
|
+
from .constant import digits_in_base, first_primes
|
|
20
|
+
|
|
21
|
+
BLOCK_RULES = ("prime", "digit", "mod_base", "digital_root")
|
|
22
|
+
CARRY_MODES = ("ceil", "signed", "none")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def blocks(primes: list[int], rule: str, base: int = 10) -> list[tuple[int, int]]:
|
|
26
|
+
"""List of (value, number_of_digits) blocks."""
|
|
27
|
+
if rule == "prime":
|
|
28
|
+
return [(p, len(digits_in_base(p, base))) for p in primes]
|
|
29
|
+
if rule == "digit":
|
|
30
|
+
return [(g, 1) for p in primes for g in digits_in_base(p, base)]
|
|
31
|
+
if rule == "mod_base":
|
|
32
|
+
return [(p % base, 1) for p in primes]
|
|
33
|
+
if rule == "digital_root":
|
|
34
|
+
if base < 3:
|
|
35
|
+
raise ValueError("digital root needs base >= 3")
|
|
36
|
+
return [(1 + (p - 1) % (base - 1), 1) for p in primes]
|
|
37
|
+
raise ValueError(f"unknown block rule {rule!r}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class SeriesTerm:
|
|
42
|
+
denominator: int # signed for the "signed" mode
|
|
43
|
+
u: float # 9-digit float summary of u_k = a_k^2 * |E_k|
|
|
44
|
+
u_exact: Fraction = Fraction(0) # exact rational u_k = a_k^2 * |E_k|
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def blockwise_series(blks: list[tuple[int, int]], base: int = 10, carry: str = "ceil") -> list[SeriesTerm]:
|
|
48
|
+
if carry not in CARRY_MODES:
|
|
49
|
+
raise ValueError(f"unknown carry mode {carry!r}")
|
|
50
|
+
total = sum(n for _, n in blks)
|
|
51
|
+
W = 2 * total + 60 # fixed-point precision, in base-`base` digits
|
|
52
|
+
S = base**W
|
|
53
|
+
target = acc = pos = 0
|
|
54
|
+
out: list[SeriesTerm] = []
|
|
55
|
+
for value, ndig in blks:
|
|
56
|
+
pos += ndig
|
|
57
|
+
if value == 0:
|
|
58
|
+
continue
|
|
59
|
+
block = value * base ** (W - pos)
|
|
60
|
+
target += block
|
|
61
|
+
if carry == "none":
|
|
62
|
+
a = (2 * base**pos + value) // (2 * value) # round(base^pos / value)
|
|
63
|
+
err = abs(block - S // a)
|
|
64
|
+
u_ex = Fraction(a * a * err, S)
|
|
65
|
+
out.append(SeriesTerm(a, (a * a * err * 10**9 // S) / 1e9, u_ex))
|
|
66
|
+
continue
|
|
67
|
+
x = target - acc
|
|
68
|
+
if carry == "ceil":
|
|
69
|
+
if x <= 0:
|
|
70
|
+
continue
|
|
71
|
+
a, sign = -(-S // x), 1
|
|
72
|
+
else:
|
|
73
|
+
if x == 0:
|
|
74
|
+
continue
|
|
75
|
+
sign = 1 if x > 0 else -1
|
|
76
|
+
a = (2 * S + abs(x)) // (2 * abs(x))
|
|
77
|
+
acc += sign * (S // a)
|
|
78
|
+
err = abs(target - acc)
|
|
79
|
+
u_ex = Fraction(a * a * err, S)
|
|
80
|
+
out.append(SeriesTerm(sign * a, (a * a * err * 10**9 // S) / 1e9, u_ex))
|
|
81
|
+
return out
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def prime_blockwise_series(
|
|
85
|
+
n_primes: int, rule: str = "prime", base: int = 10, carry: str = "ceil"
|
|
86
|
+
) -> list[SeriesTerm]:
|
|
87
|
+
"""Convenience wrapper: block-wise series built from the first `n_primes` primes."""
|
|
88
|
+
return blockwise_series(blocks(first_primes(n_primes), rule, base), base, carry)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def nico_leon_series(
|
|
92
|
+
n_primes: int, rule: str = "prime", base: int = 10, carry: str = "ceil"
|
|
93
|
+
) -> list[SeriesTerm]:
|
|
94
|
+
"""Backwards-compatible alias for ``prime_blockwise_series``."""
|
|
95
|
+
return prime_blockwise_series(n_primes, rule=rule, base=base, carry=carry)
|
ceexp/verify.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Independent re-implementations used only to cross-check expansions.py.
|
|
2
|
+
|
|
3
|
+
They use the `decimal` module with an isolated localcontext (no global state
|
|
4
|
+
mutation) and an exact Horner reconstruction of the constant from the terms.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import decimal
|
|
9
|
+
|
|
10
|
+
from .constant import int_to_digits
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def engel_decimal(digits: str, count: int) -> list[int]:
|
|
14
|
+
"""Engel expansion using an isolated local Decimal context."""
|
|
15
|
+
with decimal.localcontext() as ctx:
|
|
16
|
+
ctx.prec = len(digits) + 60
|
|
17
|
+
x = decimal.Decimal("0." + digits)
|
|
18
|
+
out = []
|
|
19
|
+
for _ in range(count):
|
|
20
|
+
a = int((1 / x).to_integral_value(rounding=decimal.ROUND_CEILING))
|
|
21
|
+
out.append(a)
|
|
22
|
+
x = a * x - 1
|
|
23
|
+
return out
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def pierce_decimal(digits: str, count: int) -> list[int]:
|
|
27
|
+
"""Pierce expansion using an isolated local Decimal context."""
|
|
28
|
+
with decimal.localcontext() as ctx:
|
|
29
|
+
ctx.prec = len(digits) + 60
|
|
30
|
+
x = decimal.Decimal("0." + digits)
|
|
31
|
+
out = []
|
|
32
|
+
for _ in range(count):
|
|
33
|
+
b = int((1 / x).to_integral_value(rounding=decimal.ROUND_FLOOR))
|
|
34
|
+
out.append(b)
|
|
35
|
+
x = 1 - b * x
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def reconstruct(terms: list[int], alternating: bool, n_digits: int) -> str:
|
|
40
|
+
"""Leading digits of 1/a1 (1 +- 1/a2 (1 +- ...)), the value encoded by Engel/Pierce terms."""
|
|
41
|
+
S = 10 ** (n_digits + 30)
|
|
42
|
+
sign = -1 if alternating else 1
|
|
43
|
+
t = S
|
|
44
|
+
for a in reversed(terms[1:]):
|
|
45
|
+
t = S + sign * (t // a)
|
|
46
|
+
return int_to_digits(t // terms[0]).zfill(n_digits + 30)[:n_digits]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def matching_digits(a: str, b: str) -> int:
|
|
50
|
+
k = 0
|
|
51
|
+
while k < min(len(a), len(b)) and a[k] == b[k]:
|
|
52
|
+
k += 1
|
|
53
|
+
return k
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ceexp
|
|
3
|
+
Version: 0.3.2
|
|
4
|
+
Summary: Interval-certified Engel, Pierce, Luroth, and continued-fraction expansions and precision benchmarks
|
|
5
|
+
Author-email: Nicolás León Parra <leonparranicolas@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Nicolas11Leon/copeland-erdos-expansions
|
|
8
|
+
Project-URL: Repository, https://github.com/Nicolas11Leon/copeland-erdos-expansions
|
|
9
|
+
Project-URL: Issues, https://github.com/Nicolas11Leon/copeland-erdos-expansions/issues
|
|
10
|
+
Keywords: number-theory,interval-arithmetic,engel-expansion,pierce-expansion,continued-fraction,precision-benchmark
|
|
11
|
+
Requires-Python: >=3.11
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
License-File: LICENSE-docs.md
|
|
15
|
+
Provides-Extra: experiments
|
|
16
|
+
Requires-Dist: numpy>=1.26; extra == "experiments"
|
|
17
|
+
Requires-Dist: scipy>=1.11; extra == "experiments"
|
|
18
|
+
Provides-Extra: benchmark
|
|
19
|
+
Requires-Dist: mpmath>=1.2; extra == "benchmark"
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# Expansions and residues of the Copeland–Erdős constant
|
|
23
|
+
|
|
24
|
+
[](https://doi.org/10.5281/zenodo.24693622)
|
|
25
|
+
|
|
26
|
+
Certified computations, proofs and reproducible experiments on integer sequences derived from the
|
|
27
|
+
**Copeland–Erdős constant** `C = 0.235711131719232931374143…`, the number obtained by writing the
|
|
28
|
+
primes one after another in base 10 (OEIS [A033308](https://oeis.org/A033308)).
|
|
29
|
+
|
|
30
|
+
**Author:** Nicolás León Parra · **Status:** pre-publication (v0.2.0) · **Code:** MIT · **Text and data:** CC BY 4.0
|
|
31
|
+
|
|
32
|
+
## What is in this repository
|
|
33
|
+
|
|
34
|
+
| Object | Definition | Status |
|
|
35
|
+
| :--- | :--- | :--- |
|
|
36
|
+
| Engel expansion of `C` | `C = 1/a₁ + 1/(a₁a₂) + 1/(a₁a₂a₃) + …` | 2,136 proved terms; not in the OEIS |
|
|
37
|
+
| Pierce expansion of `C` | `C = 1/b₁ − 1/(b₁b₂) + 1/(b₁b₂b₃) − …` | 2,155 proved terms; not in the OEIS |
|
|
38
|
+
| Greedy Egyptian-fraction expansion of `C` | `C = 1/g₁ + 1/g₂ + …`, `gₖ = ⌈1/xₖ⌉` | 20 proved terms (the last has 411,255 digits); not in the OEIS |
|
|
39
|
+
| Block-wise unit-fraction expansion | one unit fraction per block of digits of `C`, with debt carry | 4 block rules × 3 carry modes × several bases |
|
|
40
|
+
| Prime-concatenation residue | `r(n) = 10^d(n) mod pₙ`, `d(n)` = digits of the first `n` primes ([A068670](https://oeis.org/A068670)) | structure proved; tested with TestU01, PractRand and NIST STS |
|
|
41
|
+
|
|
42
|
+
In the author's working notes the block-wise expansion is called the *Nico León series* and the residue the *Nicolian residue*.
|
|
43
|
+
|
|
44
|
+
The two families are linked: the residue is exactly the rounding error of the block-wise expansion
|
|
45
|
+
without carry (proposition "the residue is the rounding error" in the paper).
|
|
46
|
+
|
|
47
|
+
## Main results
|
|
48
|
+
|
|
49
|
+
1. **Validation against accepted sequences.** The implementations reproduce, term by term, seven
|
|
50
|
+
OEIS entries: the Engel expansions of π (A006784) and √2 (A028254), the Pierce expansion of
|
|
51
|
+
√2 − 1 (A006275), the greedy expansion of Catalan's constant (A118323), the continued fraction of
|
|
52
|
+
`C` (A030168), its digits (A033308) and `d(n)` (A068670).
|
|
53
|
+
2. **Proved terms of new expansions of `C`.** Every published term is proved correct by an interval
|
|
54
|
+
certificate computed in exact arithmetic (the set of reals sharing the first `k` terms is an interval),
|
|
55
|
+
and is independently confirmed at twice the precision, by a second arithmetic engine (Python `decimal`)
|
|
56
|
+
and by reconstructing `C` from the terms to almost 10⁶ digits.
|
|
57
|
+
3. **Algebraic structure of the residue** (proved): `r(n) ≠ 0` for `pₙ ≠ 2, 5`; `r(n)` lies in the
|
|
58
|
+
subgroup generated by 10; its quadratic character is `(10/pₙ)^d(n)`; the parity of `d(n)` is constant
|
|
59
|
+
on blocks of primes with an even number of digits; `r(n) = 1` iff the period of `1/pₙ` divides `d(n)`.
|
|
60
|
+
These explain the observed 68.3 % of quadratic residues and the excess of small values quantitatively.
|
|
61
|
+
4. **A blind spot of black-box randomness tests.** The residue passes TestU01 SmallCrush, PractRand
|
|
62
|
+
(2²⁸ bytes) and the NIST STS suite, and so does a base-9 variant whose values are **all** quadratic
|
|
63
|
+
residues, a structure detectable with one line of algebra.
|
|
64
|
+
|
|
65
|
+
Full statements, proofs and limitations: [`paper/expansions-copeland-erdos.pdf`](paper/).
|
|
66
|
+
|
|
67
|
+
## Quick start
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
git clone https://github.com/Nicolas11Leon/copeland-erdos-expansions.git
|
|
71
|
+
cd copeland-erdos-expansions
|
|
72
|
+
PYTHONPATH=src python3 -m unittest discover -s tests -v
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from ceexp import copeland_erdos_digits, certified_interval, engel
|
|
77
|
+
digits = copeland_erdos_digits(20000)
|
|
78
|
+
terms = certified_interval(engel, digits) # proved terms (interval certificate)
|
|
79
|
+
print(len(terms), terms[:10]) # 311 [5, 6, 15, 15, 20, 360, 644, 807, 1508, 3651]
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The package `ceexp` needs only the Python 3.11+ standard library. The statistical experiments in
|
|
83
|
+
`experiments/` additionally use NumPy and SciPy; the third-party test suites are not redistributed
|
|
84
|
+
(see `experiments/README.md` for versions and checksums).
|
|
85
|
+
|
|
86
|
+
## Repository layout
|
|
87
|
+
|
|
88
|
+
```text
|
|
89
|
+
src/ceexp/ expansions, block-wise series, residues, independent verification engines
|
|
90
|
+
tests/ unit tests (OEIS reference values, propositions, cross-engine checks)
|
|
91
|
+
data/ b-files in OEIS format ("n a(n)") for every certified sequence
|
|
92
|
+
experiments/ scripts and logs of every experiment reported in the paper
|
|
93
|
+
paper/ LaTeX source and PDF of the technical paper
|
|
94
|
+
docs/ taxonomy of variants, applications, submission plan and drafts
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## How to cite
|
|
98
|
+
|
|
99
|
+
Archived on Zenodo: [doi:10.5281/zenodo.24693622](https://doi.org/10.5281/zenodo.24693622) (all versions; v0.2.0 is doi:10.5281/zenodo.24693623).
|
|
100
|
+
See [`CITATION.cff`](CITATION.cff) for the citation metadata.
|
|
101
|
+
|
|
102
|
+
## Resumen en español
|
|
103
|
+
|
|
104
|
+
Cálculos certificados, demostraciones y experimentos reproducibles sobre sucesiones derivadas de la
|
|
105
|
+
constante de Copeland–Erdős: sus expansiones de Engel, Pierce y voraz en fracciones egipcias (no
|
|
106
|
+
catalogadas en la OEIS), la expansión por bloques con arrastre de deuda y el residuo
|
|
107
|
+
`10^d(n) mod pₙ`, con sus propiedades algebraicas demostradas y su comportamiento ante las baterías
|
|
108
|
+
estadísticas de referencia.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
ceexp/__init__.py,sha256=Gz8t1STPzFwyVCiOzWkhEAlzs9zitRM2CjjzqbLVC5w,769
|
|
2
|
+
ceexp/benchmark.py,sha256=xw701fJtuBTWYC2SNXmj28_SJghpdpbanT4noe_7IYw,10571
|
|
3
|
+
ceexp/constant.py,sha256=DKLUOPMhRZncQAvTzTCgzD6DtRRUry1ZjfIef4azpHo,4744
|
|
4
|
+
ceexp/expansions.py,sha256=U2bBRMjMhmWDnIq5y-WNMcNTeb4pobx8cOrfltJHVwg,5250
|
|
5
|
+
ceexp/residue.py,sha256=o12WPHlDOmJ0weOHVELfiYkmBrdhvAgajUCFeSPn7KI,3563
|
|
6
|
+
ceexp/series.py,sha256=TrpMxxsnMYDCzGi-q0fqk_-vcV4n7ccZAAzGg_i1rwM,3815
|
|
7
|
+
ceexp/verify.py,sha256=Cp9RA6Nfp-_BKL84yqrrtylIxAR9LoLf0EuwWSbtim8,1733
|
|
8
|
+
ceexp-0.3.2.dist-info/licenses/LICENSE,sha256=tXocIS3oludJGmG1oYfhRCVk7FxHRD_BVKbb7Q_MKdA,1077
|
|
9
|
+
ceexp-0.3.2.dist-info/licenses/LICENSE-docs.md,sha256=zBHdNvK7amnmrb6BkSetgfZZG_nkAyoEq8J1trrXZTQ,430
|
|
10
|
+
ceexp-0.3.2.dist-info/METADATA,sha256=Yr4dbDQrIIAZOVFZInVEixpBnZVVFDL4VWaFVX2B8SE,6143
|
|
11
|
+
ceexp-0.3.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
12
|
+
ceexp-0.3.2.dist-info/entry_points.txt,sha256=aHfGml7_xMokHouFgRbieuqUp4b854z553QhruDkYME,53
|
|
13
|
+
ceexp-0.3.2.dist-info/top_level.txt,sha256=LkUeLa8hSzhg3LboVmvFN4ibJqFCgQfx9Bj7wZ8SYSc,6
|
|
14
|
+
ceexp-0.3.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nicolás León Parra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# License for text and data
|
|
2
|
+
|
|
3
|
+
The paper (`paper/`), the documentation (`docs/`) and the data files (`data/`) are licensed under the
|
|
4
|
+
Creative Commons Attribution 4.0 International License (CC BY 4.0):
|
|
5
|
+
https://creativecommons.org/licenses/by/4.0/
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2026 Nicolás León Parra.
|
|
8
|
+
|
|
9
|
+
The reference values in `tests/fixtures/oeis_reference.json` are taken from the OEIS
|
|
10
|
+
(https://oeis.org), which is licensed under CC BY-SA 4.0.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ceexp
|