checks.py

back to table · edit · history · where entries came from · files · download

8592 bytes, as of the version from 2026-10-25 19:59 (current). Recorded here, not run.

"""Independent checks for Favard constants -- numberdb.org/T501.

    sage -python checks.py            # local numbers and independent checks
    sage -python checks.py --stored   # additionally check all database rows

The Entringer triangle counts alternating permutations using exact integers.
Its first cases are controlled by enumerating permutations, and all 21 counts
are compared with the attached OEIS A000111 extract. A second exact method
solves cos(x/2)*F(x)=1+sin(x/2) coefficient by coefficient. Neither method
uses a zeta function. Independent balls use these rational coefficients and
pi at 600 bits, compared with the generator's 397-bit evaluations.

Read-back validation uses the decimal's full interval, not just its midpoint.
The client check.stored helper requires Django/database access, so this file
reads the same authoritative document via the public API instead.
"""
import os
import sys
import json
from pathlib import Path
from fractions import Fraction
from decimal import Decimal
from itertools import permutations
from math import factorial
import numberdb.sage as numberdb
from numberdb._write import to_text
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from check import exactness, measure, agrees_with, names_its_rings
from generate import FavardConstants, MAX_ORDER, WORKING_GUARD


def alternating_counts(limit):
    row = [ZZ(1)]
    counts = [ZZ(1)]
    for n in range(1, limit + 1):
        new = [ZZ(0)]
        for k in range(1, n + 1):
            new.append(new[-1] + row[n-k])
        row = new
        counts.append(row[-1])
    return counts


def series_coefficients(limit):
    """Coefficients of sec(x/2)+tan(x/2), all exact."""
    cosine = [QQ(0)] * (limit + 1)
    sine = [QQ(0)] * (limit + 1)
    for n in range(limit + 1):
        scale = QQ(1) / (ZZ(2)**n * ZZ(factorial(n)))
        if n % 2:
            sine[n] = (-1)**((n-1)//2) * scale
        else:
            cosine[n] = (-1)**(n//2) * scale
    coeffs = [QQ(1)]
    for n in range(1, limit + 1):
        coeffs.append(sine[n] - sum(cosine[j]*coeffs[n-j]
                                    for j in range(1, n+1)))
    return coeffs


def decimal_bounds(text):
    """Exact endpoints of NumberDB's last-place uncertainty interval."""
    text = str(text)
    if '.' not in text and 'e' not in text.lower():
        q = QQ(text)
        return q, q
    d = Decimal(text)
    f = Fraction(d)
    mid = QQ(f.numerator) / f.denominator
    unit = QQ(10)**d.as_tuple().exponent
    return mid-unit, mid+unit


def number_text(entry):
    return entry['number'] if isinstance(entry, dict) else entry


def main():
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        os.environ['NUMBERDB_API_KEY'] = sys.stdin.read().strip()
    root = Path(__file__).resolve().parent
    counts = alternating_counts(MAX_ORDER)
    assert counts[:6] == [1, 1, 1, 2, 5, 16]
    for n in range(9):
        counted = sum(all((p[j] < p[j+1]) == (j % 2 == 0)
                          for j in range(n-1))
                      for p in permutations(range(n)))
        assert counted == counts[n], (n, counted, counts[n])
    print('Controls: explicit alternating-permutation counts, orders 0..8, pass.')
    oeis = {}
    for line in (root/'oeis-a000111-0-20.txt').read_text().splitlines():
        if line and not line.startswith('#'):
            n, a = line.split(); oeis[int(n)] = ZZ(a)
    assert len(oeis) == MAX_ORDER+1
    assert not agrees_with(dict(enumerate(counts)), lambda r: oeis[r])
    coefficients = [QQ(counts[r]) / (ZZ(2)**r * ZZ(factorial(r)))
                    for r in range(MAX_ORDER+1)]
    series = series_coefficients(MAX_ORDER)
    assert not agrees_with(dict(enumerate(coefficients)), lambda r: series[r])
    assert coefficients[:6] == [QQ(1), QQ(1)/2, QQ(1)/8, QQ(1)/24,
                                QQ(5)/384, QQ(1)/240]
    assert not exactness(coefficients)
    print('All 21 OEIS counts and all 21 exact generating-function coefficients agree.')

    gen = FavardConstants()
    values = {int(p['r']): gen.value(p, 100) for p in gen.enumerate()}
    assert not names_its_rings(str(root/'generate.py'))
    assert not exactness(values)
    high = RealBallField(600)
    refs = {r: high(coefficients[r])*high.pi()**r for r in values}
    texts = {}
    radii = []
    for r, entry in values.items():
        val = entry['number'] if isinstance(entry, dict) else entry
        ref = refs[r]
        assert ref.is_finite() and high(ref.rad()) < high(10)**(-170), r
        if r:
            assert val.is_finite() and high(val.rad()) < high(10)**(-110), r
            assert high(val).overlaps(ref), r
            radii.append((val.rad(), r))
        else:
            assert val == 1
        text = to_text(val, 100)
        lo, hi = decimal_bounds(text)
        assert lo <= ref.lower().exact_rational() and ref.upper().exact_rational() <= hi, r
        if r:
            assert len(Decimal(text).as_tuple().digits) == 100
        texts[str(r)] = text
    print('All 21 independent values lie inside the written intervals; 20 have 100 digits.')
    print('Working bits:', numberdb.bits(100,losing=WORKING_GUARD))
    print('Maximum radius and its order:', max(radii))
    print('Measured raw values:', measure(values))
    print('Measured written values:', measure(texts))

    # The corpus holds the exact Euler polynomials, a third independent source.
    euler_doc = numberdb.table('T115')
    ring = PolynomialRing(QQ, 'x')
    for r in values:
        polynomial = ring(str(number_text(euler_doc['Numbers'][str(r)])))
        at = QQ(0) if r % 2 else QQ(1)/2
        coefficient = abs(polynomial(at)) / ZZ(factorial(r))
        assert coefficient == coefficients[r], r
    print('All 21 rational coefficients agree with the stored Euler polynomials T115.')

    # Check the direction relative to the limit and monotonicity of each parity.
    limit = 4/high.pi()
    for r in range(1,MAX_ORDER+1):
        assert (refs[r] > limit) if r%2 else (refs[r] < limit)
        if r >= 2:
            assert (refs[r] < refs[r-2]) if r%2 else (refs[r] > refs[r-2])
    print('Odd orders decrease and even orders increase toward 4/pi on the stored range.')

    stored_balls = None
    if '--stored' in sys.argv or os.environ.get('FAVARD_CHECK_STORED') == '1':
        doc = numberdb.table('T501')
        entries = doc['Numbers']
        assert list(entries) == [str(r) for r in range(MAX_ORDER+1)]
        stored_balls = {}
        for r in values:
            text = number_text(entries[str(r)])
            lo, hi = decimal_bounds(text)
            assert lo <= refs[r].lower().exact_rational() and refs[r].upper().exact_rational() <= hi, r
            if r == 0: assert str(text) == '1'
            else: assert len(Decimal(text).as_tuple().digits) == 100
            stored_balls[r] = high(lo).union(high(hi))
        for r in range(1, MAX_ORDER+1):
            assert (stored_balls[r] > limit) if r%2 else (stored_balls[r] < limit)
            if r >= 2:
                assert ((stored_balls[r] < stored_balls[r-2]) if r%2
                        else (stored_balls[r] > stored_balls[r-2]))
        print('Read-back: all 21 stored intervals enclose the independent values; order and parity claims pass.')
        report = gen.verify(sample=None)
        assert report.ok, report
        print(report)
    if '--companion' in sys.argv or '--stored' in sys.argv:
        other = numberdb.table('T500')['Numbers']
        checked = 0
        for n in range(2, MAX_ORDER+1):
            for k in range(1,n):
                lo, hi = decimal_bounds(number_text(other[str(n)][str(k)]))
                exact_power = coefficients[n-k]**n / coefficients[n]**(n-k)
                assert lo**n <= exact_power <= hi**n, (n,k)
                kv = stored_balls if stored_balls is not None else refs
                lhs = high(lo).union(high(hi))**n * kv[n]**(n-k)
                rhs = kv[n-k]**n
                assert lhs.is_finite() and rhs.is_finite()
                assert high(lhs.rad()) < high(10)**(-85)
                assert high(rhs.rad()) < high(10)**(-85)
                assert lhs.overlaps(rhs), (n,k)
                checked += 1
        assert checked == 190
        print('All 190 Landau-Kolmogorov relations agree, including exact rational nth powers.')
    print('VALUES_JSON='+json.dumps(texts,sort_keys=False))
    return 0


if __name__ == '__main__':
    raise SystemExit(main())