ceexp 0.3.2__tar.gz → 0.3.3__tar.gz

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.
Files changed (26) hide show
  1. {ceexp-0.3.2/src/ceexp.egg-info → ceexp-0.3.3}/PKG-INFO +1 -1
  2. {ceexp-0.3.2 → ceexp-0.3.3}/pyproject.toml +1 -1
  3. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp/__init__.py +7 -3
  4. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp/benchmark.py +35 -18
  5. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp/expansions.py +1 -2
  6. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp/series.py +10 -6
  7. {ceexp-0.3.2 → ceexp-0.3.3/src/ceexp.egg-info}/PKG-INFO +1 -1
  8. {ceexp-0.3.2 → ceexp-0.3.3}/tests/test_expansions.py +6 -4
  9. {ceexp-0.3.2 → ceexp-0.3.3}/tests/test_properties.py +37 -7
  10. {ceexp-0.3.2 → ceexp-0.3.3}/LICENSE +0 -0
  11. {ceexp-0.3.2 → ceexp-0.3.3}/LICENSE-docs.md +0 -0
  12. {ceexp-0.3.2 → ceexp-0.3.3}/README.md +0 -0
  13. {ceexp-0.3.2 → ceexp-0.3.3}/setup.cfg +0 -0
  14. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp/constant.py +0 -0
  15. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp/residue.py +0 -0
  16. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp/verify.py +0 -0
  17. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp.egg-info/SOURCES.txt +0 -0
  18. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp.egg-info/dependency_links.txt +0 -0
  19. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp.egg-info/entry_points.txt +0 -0
  20. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp.egg-info/requires.txt +0 -0
  21. {ceexp-0.3.2 → ceexp-0.3.3}/src/ceexp.egg-info/top_level.txt +0 -0
  22. {ceexp-0.3.2 → ceexp-0.3.3}/tests/test_benchmark.py +0 -0
  23. {ceexp-0.3.2 → ceexp-0.3.3}/tests/test_champernowne_comparison.py +0 -0
  24. {ceexp-0.3.2 → ceexp-0.3.3}/tests/test_reference.py +0 -0
  25. {ceexp-0.3.2 → ceexp-0.3.3}/tests/test_theorems.py +0 -0
  26. {ceexp-0.3.2 → ceexp-0.3.3}/tests/test_variants_and_arithmetic.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ceexp
3
- Version: 0.3.2
3
+ Version: 0.3.3
4
4
  Summary: Interval-certified Engel, Pierce, Luroth, and continued-fraction expansions and precision benchmarks
5
5
  Author-email: Nicolás León Parra <leonparranicolas@gmail.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ceexp"
7
- version = "0.3.2"
7
+ version = "0.3.3"
8
8
  description = "Interval-certified Engel, Pierce, Luroth, and continued-fraction expansions and precision benchmarks"
9
9
  authors = [{ name = "Nicolás León Parra", email = "leonparranicolas@gmail.com" }]
10
10
  license = { text = "MIT" }
@@ -1,7 +1,8 @@
1
1
  """ceexp: expansions, block-wise unit-fraction series and residues of the Copeland-Erdos constant."""
2
+ from importlib.metadata import PackageNotFoundError, version as _pkg_version
3
+
2
4
  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
+ digits_in_base, first_primes, int_from_digits, int_to_digits, primes_up_to)
5
6
  from .expansions import (certified, certified_interval, continued_fraction, engel,
6
7
  greedy_egyptian, luroth, pierce)
7
8
  from .residue import (legendre, multiplicative_order, residues, rounding_identity_holds,
@@ -9,4 +10,7 @@ from .residue import (legendre, multiplicative_order, residues, rounding_identit
9
10
  from .series import (BLOCK_RULES, CARRY_MODES, blocks, blockwise_series, nico_leon_series,
10
11
  prime_blockwise_series)
11
12
 
12
- __version__ = "0.3.2"
13
+ try:
14
+ __version__ = _pkg_version("ceexp")
15
+ except PackageNotFoundError: # pragma: no cover - editable / uninstalled checkout
16
+ __version__ = "0.3.3"
@@ -23,7 +23,7 @@ try:
23
23
  except ImportError: # pragma: no cover - optional dependency
24
24
  mpmath = None
25
25
 
26
- from .constant import copeland_erdos_digits, digits_in_base
26
+ from .constant import copeland_erdos_digits, digits_in_base, int_to_digits
27
27
  from .expansions import (
28
28
  certified_interval,
29
29
  continued_fraction,
@@ -51,8 +51,6 @@ def _champernowne_digits(n_digits: int, base: int) -> list[int]:
51
51
 
52
52
 
53
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
54
  def to_int(seq: list[int], cache: dict[int, int]) -> int:
57
55
  n = len(seq)
58
56
  if n <= 64:
@@ -68,7 +66,7 @@ def _base_digits_to_decimal_str(digits: list[int], base: int, n_digits: int) ->
68
66
 
69
67
  num = to_int(digits, {})
70
68
  scaled = (num * (10**n_digits)) // (base ** len(digits))
71
- return str(scaled).zfill(n_digits)
69
+ return int_to_digits(scaled).zfill(n_digits)
72
70
 
73
71
 
74
72
  def run_float64(digits: str, mode: str, max_terms: int) -> list[int]:
@@ -183,15 +181,21 @@ def first_divergence_index(truth: list[int], candidate: list[int]) -> int | None
183
181
  return None
184
182
 
185
183
 
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()
184
+ def _measure(
185
+ fn: Callable[[], list[int]], measure_memory: bool = False
186
+ ) -> tuple[list[int], float, float | None]:
187
+ """Run `fn` cleanly for timing; optionally measure peak KB in a separate pass."""
189
188
  ts = time.monotonic()
190
189
  res = fn()
191
190
  ms = round((time.monotonic() - ts) * 1000, 2)
192
- _, peak = tracemalloc.get_traced_memory()
193
- tracemalloc.stop()
194
- return res, ms, round(peak / 1024, 1)
191
+ peak_kb: float | None = None
192
+ if measure_memory:
193
+ tracemalloc.start()
194
+ fn()
195
+ _, peak = tracemalloc.get_traced_memory()
196
+ tracemalloc.stop()
197
+ peak_kb = round(peak / 1024, 1)
198
+ return res, ms, peak_kb
195
199
 
196
200
 
197
201
  def build_benchmark_constants(n_digits: int) -> dict[str, str]:
@@ -214,6 +218,7 @@ def run_benchmark(
214
218
  decimal_precs: tuple[int, ...] = (50, 200, 1000),
215
219
  trunc_digits: tuple[int, ...] = (500, 2000),
216
220
  modes: tuple[str, ...] = ("engel", "pierce", "luroth", "continued_fraction"),
221
+ measure_memory: bool = False,
217
222
  ) -> dict[str, object]:
218
223
  """Benchmark uncertified engines against interval-certified ground truth."""
219
224
  constants = build_benchmark_constants(n_digits)
@@ -227,19 +232,22 @@ def run_benchmark(
227
232
  case_entry: dict[str, object] = {}
228
233
  for mode in modes:
229
234
  exp_fn = EXPANSIONS[mode]
230
- truth, cert_ms, cert_kb = _measure(lambda: certified_interval(exp_fn, digits))
235
+ truth, cert_ms, cert_kb = _measure(
236
+ lambda: certified_interval(exp_fn, digits), measure_memory=measure_memory
237
+ )
231
238
  max_terms = len(truth)
232
239
  engines: dict[str, object] = {}
233
240
 
234
241
  def record(label: str, fn: Callable[[], list[int]]) -> None:
235
- cand, ms, kb = _measure(fn)
242
+ cand, ms, kb = _measure(fn, measure_memory=measure_memory)
236
243
  div_k = first_divergence_index(truth, cand)
237
244
  entry: dict[str, object] = {
238
245
  "terms_produced": len(cand),
239
246
  "first_divergence_k": div_k,
240
247
  "elapsed_ms": ms,
241
- "peak_kb": kb,
242
248
  }
249
+ if kb is not None:
250
+ entry["peak_kb"] = kb
243
251
  if div_k is not None:
244
252
  entry["truth_term"] = str(truth[div_k - 1])[:24]
245
253
  entry["engine_term"] = str(cand[div_k - 1])[:24]
@@ -265,19 +273,23 @@ def run_benchmark(
265
273
  ),
266
274
  )
267
275
 
268
- case_entry[mode] = {
276
+ entry_mode: dict[str, object] = {
269
277
  "certified_terms": max_terms,
270
278
  "certified_elapsed_ms": cert_ms,
271
- "certified_peak_kb": cert_kb,
272
279
  "engines": engines,
273
280
  }
281
+ if cert_kb is not None:
282
+ entry_mode["certified_peak_kb"] = cert_kb
283
+ case_entry[mode] = entry_mode
274
284
  report["cases"][name] = case_entry
275
285
  return report
276
286
 
277
287
 
278
288
  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)
289
+ args = [a for a in sys.argv[1:] if a != "--memory"]
290
+ measure_memory = "--memory" in sys.argv[1:]
291
+ n_digits = int(args[0]) if args else 50_000
292
+ report = run_benchmark(n_digits=n_digits, measure_memory=measure_memory)
281
293
 
282
294
  repo_root = Path(__file__).resolve().parent.parent.parent
283
295
  if (repo_root / "pyproject.toml").exists():
@@ -298,9 +310,14 @@ def main() -> None:
298
310
  else f"{eng}=ok({info['terms_produced']})"
299
311
  for eng, info in data["engines"].items()
300
312
  )
313
+ mem_str = (
314
+ f", {data['certified_peak_kb']:.0f}KB"
315
+ if "certified_peak_kb" in data
316
+ else ""
317
+ )
301
318
  print(
302
319
  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}"
320
+ f"({data['certified_elapsed_ms']:.0f}ms{mem_str}) -> {summary}"
304
321
  )
305
322
  print(f"Saved report to {out_path}")
306
323
 
@@ -3,7 +3,7 @@
3
3
  Every function takes the real as an exact rational n/d (typically d = 10^N for N known
4
4
  digits) and returns only terms that the available precision certifies: a term is emitted
5
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).
6
+ Use ``certified_interval`` for a formal interval proof over [0.digits, 0.digits + 10^-N].
7
7
 
8
8
  Definitions (x > 0):
9
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
@@ -161,5 +161,4 @@ __all__ = [
161
161
  "certified",
162
162
  "certified_interval",
163
163
  "common_prefix",
164
- "log10",
165
164
  ]
@@ -13,7 +13,7 @@ Block rules:
13
13
  """
14
14
  from __future__ import annotations
15
15
 
16
- from dataclasses import dataclass
16
+ from dataclasses import dataclass, field
17
17
  from fractions import Fraction
18
18
 
19
19
  from .constant import digits_in_base, first_primes
@@ -41,7 +41,13 @@ def blocks(primes: list[int], rule: str, base: int = 10) -> list[tuple[int, int]
41
41
  class SeriesTerm:
42
42
  denominator: int # signed for the "signed" mode
43
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|
44
+ _u_num: int = field(default=0, repr=False, compare=False)
45
+ _u_den: int = field(default=1, repr=False, compare=False)
46
+
47
+ @property
48
+ def u_exact(self) -> Fraction:
49
+ """Exact rational u_k = a_k^2 * |E_k|, computed lazily on access."""
50
+ return Fraction(self._u_num, self._u_den)
45
51
 
46
52
 
47
53
  def blockwise_series(blks: list[tuple[int, int]], base: int = 10, carry: str = "ceil") -> list[SeriesTerm]:
@@ -61,8 +67,7 @@ def blockwise_series(blks: list[tuple[int, int]], base: int = 10, carry: str = "
61
67
  if carry == "none":
62
68
  a = (2 * base**pos + value) // (2 * value) # round(base^pos / value)
63
69
  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))
70
+ out.append(SeriesTerm(a, (a * a * err * 10**9 // S) / 1e9, a * a * err, S))
66
71
  continue
67
72
  x = target - acc
68
73
  if carry == "ceil":
@@ -76,8 +81,7 @@ def blockwise_series(blks: list[tuple[int, int]], base: int = 10, carry: str = "
76
81
  a = (2 * S + abs(x)) // (2 * abs(x))
77
82
  acc += sign * (S // a)
78
83
  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))
84
+ out.append(SeriesTerm(sign * a, (a * a * err * 10**9 // S) / 1e9, a * a * err, S))
81
85
  return out
82
86
 
83
87
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ceexp
3
- Version: 0.3.2
3
+ Version: 0.3.3
4
4
  Summary: Interval-certified Engel, Pierce, Luroth, and continued-fraction expansions and precision benchmarks
5
5
  Author-email: Nicolás León Parra <leonparranicolas@gmail.com>
6
6
  License: MIT
@@ -10,14 +10,14 @@ DIGITS = copeland_erdos_digits(6000)
10
10
 
11
11
  class TestExpansions(unittest.TestCase):
12
12
  def test_engel_two_engines_and_reconstruction(self):
13
- terms = certified(engel, DIGITS)
13
+ terms = certified_interval(engel, DIGITS)
14
14
  self.assertGreater(len(terms), 100)
15
15
  self.assertEqual(terms[:6], [5, 6, 15, 15, 20, 360])
16
16
  self.assertEqual(engel_decimal(DIGITS, len(terms)), terms)
17
17
  self.assertGreater(matching_digits(reconstruct(terms, False, 6000), DIGITS), 2900)
18
18
 
19
19
  def test_pierce_two_engines_and_reconstruction(self):
20
- terms = certified(pierce, DIGITS)
20
+ terms = certified_interval(pierce, DIGITS)
21
21
  self.assertGreater(len(terms), 100)
22
22
  self.assertEqual(terms[:6], [4, 17, 35, 133, 611, 725])
23
23
  self.assertEqual(pierce_decimal(DIGITS, len(terms)), terms)
@@ -25,7 +25,9 @@ class TestExpansions(unittest.TestCase):
25
25
 
26
26
  def test_interval_certificate_agrees_with_precision_doubling(self):
27
27
  for f in (engel, pierce, greedy_egyptian):
28
- a, b = certified_interval(f, DIGITS), certified(f, DIGITS)
28
+ a = certified_interval(f, DIGITS)
29
+ with self.assertWarns(DeprecationWarning):
30
+ b = certified(f, DIGITS)
29
31
  k = min(len(a), len(b))
30
32
  self.assertGreater(k, 10)
31
33
  self.assertEqual(a[:k], b[:k], f.__name__)
@@ -37,7 +39,7 @@ class TestExpansions(unittest.TestCase):
37
39
  self.assertEqual(long[: len(short)], short, f.__name__)
38
40
 
39
41
  def test_greedy_first_terms(self):
40
- terms = certified(greedy_egyptian, DIGITS)
42
+ terms = certified_interval(greedy_egyptian, DIGITS)
41
43
  self.assertEqual(terms[:5], [5, 29, 815, 725041, 857823500393])
42
44
 
43
45
 
@@ -4,13 +4,16 @@ import decimal
4
4
  import random
5
5
  import sys
6
6
  import unittest
7
+ from fractions import Fraction
8
+ from math import isqrt
7
9
  from pathlib import Path
8
10
 
9
11
  ROOT = Path(__file__).resolve().parent.parent
10
12
  sys.path.insert(0, str(ROOT / "src"))
11
13
 
12
14
  import ceexp # noqa: E402
13
- from ceexp import verify # noqa: E402
15
+ from ceexp import benchmark, verify # noqa: E402
16
+ from ceexp.residue import _prime_factors # noqa: E402
14
17
 
15
18
 
16
19
  class TestProperties(unittest.TestCase):
@@ -32,6 +35,15 @@ class TestProperties(unittest.TestCase):
32
35
  self.assertEqual(ceexp.int_to_digits(parsed), big_str)
33
36
  self.assertEqual(sys.get_int_max_str_digits(), orig_max_digits)
34
37
 
38
+ # Benchmark must also leave sys.get_int_max_str_digits untouched.
39
+ benchmark.run_benchmark(
40
+ n_digits=5000,
41
+ decimal_precs=(50,),
42
+ trunc_digits=(500,),
43
+ modes=("engel",),
44
+ )
45
+ self.assertEqual(sys.get_int_max_str_digits(), orig_max_digits)
46
+
35
47
  def test_interval_certificate_property_random_reals(self) -> None:
36
48
  rng = random.Random(2026)
37
49
  expansions = (
@@ -44,7 +56,6 @@ class TestProperties(unittest.TestCase):
44
56
  prefix = "".join(str(rng.randrange(10)) for _ in range(250))
45
57
  if set(prefix) <= {"0"}:
46
58
  continue
47
- # Pick a random interior point inside (L, U) by appending 40 random digits.
48
59
  interior = prefix + "".join(str(rng.randrange(10)) for _ in range(40))
49
60
  n_int = ceexp.int_from_digits(interior)
50
61
  d_int = 10 ** len(interior)
@@ -55,6 +66,23 @@ class TestProperties(unittest.TestCase):
55
66
  inner_terms = exp_fn(n_int, d_int)
56
67
  self.assertEqual(inner_terms[: len(cert)], cert)
57
68
 
69
+ def test_luroth_external_reference_and_reconstruction(self) -> None:
70
+ # 2/5 = 0.4 has the exact periodic Luroth expansion [3, 3, 3, ...].
71
+ self.assertEqual(ceexp.luroth(2 * 10**60, 5 * 10**60)[:10], [3] * 10)
72
+
73
+ # Reconstruct sqrt(2) - 1 from its certified Luroth terms and verify digits.
74
+ K = 200
75
+ sqrt2_m1 = ceexp.int_to_digits(isqrt(2 * 10 ** (2 * K)) - 10**K).zfill(K)
76
+ terms = ceexp.certified_interval(ceexp.luroth, sqrt2_m1)
77
+ self.assertGreater(len(terms), 80)
78
+ val = Fraction(0)
79
+ prefix_prod = 1
80
+ for a in terms[:40]:
81
+ val += Fraction(1, a * prefix_prod)
82
+ prefix_prod *= a * (a - 1)
83
+ recon_digits = ceexp.int_to_digits((val.numerator * 10**40) // val.denominator).zfill(40)
84
+ self.assertEqual(recon_digits[:35], sqrt2_m1[:35])
85
+
58
86
  def test_series_u_exact_property_and_alias(self) -> None:
59
87
  for rule in ("prime", "digit", "mod_base", "digital_root"):
60
88
  for carry in ("ceil", "signed", "none"):
@@ -62,18 +90,20 @@ class TestProperties(unittest.TestCase):
62
90
  s2 = ceexp.nico_leon_series(15, rule=rule, base=10, carry=carry)
63
91
  self.assertEqual(s1, s2)
64
92
  for term in s1:
93
+ a = abs(term.denominator)
65
94
  self.assertGreaterEqual(term.u_exact, 0)
66
- self.assertLess(term.u_exact, 1)
95
+ # Proven bound from Prop 6: u_k < a / (a - 1) for a >= 2.
96
+ if a >= 2:
97
+ self.assertLess(term.u_exact, Fraction(a, a - 1))
67
98
  self.assertAlmostEqual(float(term.u_exact), term.u, places=8)
68
99
 
69
- def test_multiplicative_order_large_primes(self) -> None:
70
- # Primes > 10^12 where naive sqrt(p) trial division is slow.
100
+ def test_multiplicative_order_large_primes_exact_minimality(self) -> None:
71
101
  for p in (1_000_000_000_039, 100_000_000_000_031):
72
102
  ord_10 = ceexp.multiplicative_order(10, p)
73
103
  self.assertEqual((p - 1) % ord_10, 0)
74
104
  self.assertEqual(pow(10, ord_10, p), 1)
75
- # Verify minimality by checking no prime divisor of ord_10 reduces it.
76
- self.assertGreater(ord_10, 1)
105
+ for q in _prime_factors(ord_10):
106
+ self.assertNotEqual(pow(10, ord_10 // q, p), 1)
77
107
 
78
108
 
79
109
  if __name__ == "__main__":
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes