ceexp 0.3.2__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.
- ceexp-0.3.2/LICENSE +21 -0
- ceexp-0.3.2/LICENSE-docs.md +10 -0
- ceexp-0.3.2/PKG-INFO +108 -0
- ceexp-0.3.2/README.md +87 -0
- ceexp-0.3.2/pyproject.toml +35 -0
- ceexp-0.3.2/setup.cfg +4 -0
- ceexp-0.3.2/src/ceexp/__init__.py +12 -0
- ceexp-0.3.2/src/ceexp/benchmark.py +309 -0
- ceexp-0.3.2/src/ceexp/constant.py +139 -0
- ceexp-0.3.2/src/ceexp/expansions.py +165 -0
- ceexp-0.3.2/src/ceexp/residue.py +121 -0
- ceexp-0.3.2/src/ceexp/series.py +95 -0
- ceexp-0.3.2/src/ceexp/verify.py +53 -0
- ceexp-0.3.2/src/ceexp.egg-info/PKG-INFO +108 -0
- ceexp-0.3.2/src/ceexp.egg-info/SOURCES.txt +24 -0
- ceexp-0.3.2/src/ceexp.egg-info/dependency_links.txt +1 -0
- ceexp-0.3.2/src/ceexp.egg-info/entry_points.txt +2 -0
- ceexp-0.3.2/src/ceexp.egg-info/requires.txt +7 -0
- ceexp-0.3.2/src/ceexp.egg-info/top_level.txt +1 -0
- ceexp-0.3.2/tests/test_benchmark.py +68 -0
- ceexp-0.3.2/tests/test_champernowne_comparison.py +65 -0
- ceexp-0.3.2/tests/test_expansions.py +73 -0
- ceexp-0.3.2/tests/test_properties.py +80 -0
- ceexp-0.3.2/tests/test_reference.py +71 -0
- ceexp-0.3.2/tests/test_theorems.py +51 -0
- ceexp-0.3.2/tests/test_variants_and_arithmetic.py +59 -0
ceexp-0.3.2/LICENSE
ADDED
|
@@ -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.
|
ceexp-0.3.2/PKG-INFO
ADDED
|
@@ -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.
|
ceexp-0.3.2/README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# Expansions and residues of the Copeland–Erdős constant
|
|
2
|
+
|
|
3
|
+
[](https://doi.org/10.5281/zenodo.24693622)
|
|
4
|
+
|
|
5
|
+
Certified computations, proofs and reproducible experiments on integer sequences derived from the
|
|
6
|
+
**Copeland–Erdős constant** `C = 0.235711131719232931374143…`, the number obtained by writing the
|
|
7
|
+
primes one after another in base 10 (OEIS [A033308](https://oeis.org/A033308)).
|
|
8
|
+
|
|
9
|
+
**Author:** Nicolás León Parra · **Status:** pre-publication (v0.2.0) · **Code:** MIT · **Text and data:** CC BY 4.0
|
|
10
|
+
|
|
11
|
+
## What is in this repository
|
|
12
|
+
|
|
13
|
+
| Object | Definition | Status |
|
|
14
|
+
| :--- | :--- | :--- |
|
|
15
|
+
| Engel expansion of `C` | `C = 1/a₁ + 1/(a₁a₂) + 1/(a₁a₂a₃) + …` | 2,136 proved terms; not in the OEIS |
|
|
16
|
+
| Pierce expansion of `C` | `C = 1/b₁ − 1/(b₁b₂) + 1/(b₁b₂b₃) − …` | 2,155 proved terms; not in the OEIS |
|
|
17
|
+
| 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 |
|
|
18
|
+
| 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 |
|
|
19
|
+
| 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 |
|
|
20
|
+
|
|
21
|
+
In the author's working notes the block-wise expansion is called the *Nico León series* and the residue the *Nicolian residue*.
|
|
22
|
+
|
|
23
|
+
The two families are linked: the residue is exactly the rounding error of the block-wise expansion
|
|
24
|
+
without carry (proposition "the residue is the rounding error" in the paper).
|
|
25
|
+
|
|
26
|
+
## Main results
|
|
27
|
+
|
|
28
|
+
1. **Validation against accepted sequences.** The implementations reproduce, term by term, seven
|
|
29
|
+
OEIS entries: the Engel expansions of π (A006784) and √2 (A028254), the Pierce expansion of
|
|
30
|
+
√2 − 1 (A006275), the greedy expansion of Catalan's constant (A118323), the continued fraction of
|
|
31
|
+
`C` (A030168), its digits (A033308) and `d(n)` (A068670).
|
|
32
|
+
2. **Proved terms of new expansions of `C`.** Every published term is proved correct by an interval
|
|
33
|
+
certificate computed in exact arithmetic (the set of reals sharing the first `k` terms is an interval),
|
|
34
|
+
and is independently confirmed at twice the precision, by a second arithmetic engine (Python `decimal`)
|
|
35
|
+
and by reconstructing `C` from the terms to almost 10⁶ digits.
|
|
36
|
+
3. **Algebraic structure of the residue** (proved): `r(n) ≠ 0` for `pₙ ≠ 2, 5`; `r(n)` lies in the
|
|
37
|
+
subgroup generated by 10; its quadratic character is `(10/pₙ)^d(n)`; the parity of `d(n)` is constant
|
|
38
|
+
on blocks of primes with an even number of digits; `r(n) = 1` iff the period of `1/pₙ` divides `d(n)`.
|
|
39
|
+
These explain the observed 68.3 % of quadratic residues and the excess of small values quantitatively.
|
|
40
|
+
4. **A blind spot of black-box randomness tests.** The residue passes TestU01 SmallCrush, PractRand
|
|
41
|
+
(2²⁸ bytes) and the NIST STS suite, and so does a base-9 variant whose values are **all** quadratic
|
|
42
|
+
residues, a structure detectable with one line of algebra.
|
|
43
|
+
|
|
44
|
+
Full statements, proofs and limitations: [`paper/expansions-copeland-erdos.pdf`](paper/).
|
|
45
|
+
|
|
46
|
+
## Quick start
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
git clone https://github.com/Nicolas11Leon/copeland-erdos-expansions.git
|
|
50
|
+
cd copeland-erdos-expansions
|
|
51
|
+
PYTHONPATH=src python3 -m unittest discover -s tests -v
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from ceexp import copeland_erdos_digits, certified_interval, engel
|
|
56
|
+
digits = copeland_erdos_digits(20000)
|
|
57
|
+
terms = certified_interval(engel, digits) # proved terms (interval certificate)
|
|
58
|
+
print(len(terms), terms[:10]) # 311 [5, 6, 15, 15, 20, 360, 644, 807, 1508, 3651]
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The package `ceexp` needs only the Python 3.11+ standard library. The statistical experiments in
|
|
62
|
+
`experiments/` additionally use NumPy and SciPy; the third-party test suites are not redistributed
|
|
63
|
+
(see `experiments/README.md` for versions and checksums).
|
|
64
|
+
|
|
65
|
+
## Repository layout
|
|
66
|
+
|
|
67
|
+
```text
|
|
68
|
+
src/ceexp/ expansions, block-wise series, residues, independent verification engines
|
|
69
|
+
tests/ unit tests (OEIS reference values, propositions, cross-engine checks)
|
|
70
|
+
data/ b-files in OEIS format ("n a(n)") for every certified sequence
|
|
71
|
+
experiments/ scripts and logs of every experiment reported in the paper
|
|
72
|
+
paper/ LaTeX source and PDF of the technical paper
|
|
73
|
+
docs/ taxonomy of variants, applications, submission plan and drafts
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## How to cite
|
|
77
|
+
|
|
78
|
+
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).
|
|
79
|
+
See [`CITATION.cff`](CITATION.cff) for the citation metadata.
|
|
80
|
+
|
|
81
|
+
## Resumen en español
|
|
82
|
+
|
|
83
|
+
Cálculos certificados, demostraciones y experimentos reproducibles sobre sucesiones derivadas de la
|
|
84
|
+
constante de Copeland–Erdős: sus expansiones de Engel, Pierce y voraz en fracciones egipcias (no
|
|
85
|
+
catalogadas en la OEIS), la expansión por bloques con arrastre de deuda y el residuo
|
|
86
|
+
`10^d(n) mod pₙ`, con sus propiedades algebraicas demostradas y su comportamiento ante las baterías
|
|
87
|
+
estadísticas de referencia.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ceexp"
|
|
7
|
+
version = "0.3.2"
|
|
8
|
+
description = "Interval-certified Engel, Pierce, Luroth, and continued-fraction expansions and precision benchmarks"
|
|
9
|
+
authors = [{ name = "Nicolás León Parra", email = "leonparranicolas@gmail.com" }]
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
readme = "README.md"
|
|
12
|
+
requires-python = ">=3.11"
|
|
13
|
+
keywords = [
|
|
14
|
+
"number-theory",
|
|
15
|
+
"interval-arithmetic",
|
|
16
|
+
"engel-expansion",
|
|
17
|
+
"pierce-expansion",
|
|
18
|
+
"continued-fraction",
|
|
19
|
+
"precision-benchmark",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://github.com/Nicolas11Leon/copeland-erdos-expansions"
|
|
24
|
+
Repository = "https://github.com/Nicolas11Leon/copeland-erdos-expansions"
|
|
25
|
+
Issues = "https://github.com/Nicolas11Leon/copeland-erdos-expansions/issues"
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
ceexp-bench = "ceexp.benchmark:main"
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
experiments = ["numpy>=1.26", "scipy>=1.11"]
|
|
32
|
+
benchmark = ["mpmath>=1.2"]
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
ceexp-0.3.2/setup.cfg
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"
|
|
@@ -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()
|