generate.py

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

3559 bytes, as of the version from 2026-12-02 04:01 (current). Recorded here, not run.

"""Generate T885: Arithmetic-progression continued fractions.

Requires SageMath and numberdb (sage -pip install numberdb).
  sage -python generate.py            # compute and check all 300 entries offline
  sage -python generate.py --verify   # compare all entries with the target
  sage -python generate.py --publish  # explicitly fill the authorized target

F(a,d)=[0;a,a+d,a+2d,...], a,d positive integers in that order.
Enumerate a+d=2,...,25, increasing a within each sum. The finite height is
a reference budget, not a restriction of the natural mathematical domain.
Consecutive convergents bound the infinite simple continued fraction.
All recurrence arithmetic uses Sage integers and all endpoints use exact
rationals. Stop at absolute bracket width < 10^(-digits-12); there is no
floating-point working precision or unproved numerical tail assumption.
Return the exact rational enclosure, not a claim that the limit is rational.
See Hetyei, arXiv:1211.2494, section 1.1, and NIST DLMF 10.33.1.
Session credentials and engine/model attribution belong in the environment.
"""
import os
import sys
from fractions import Fraction

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


def convergent_bracket(a, d, digits=100):
    a, d = ZZ(a), ZZ(d)
    if a <= 0 or d <= 0:
        raise ValueError('a and d must be positive integers')
    p0, p1 = ZZ(1), ZZ(0)
    q0, q1 = ZZ(0), ZZ(1)
    threshold = QQ(1) / ZZ(10)**(int(digits)+12)
    previous = QQ(0)
    for n in range(1, 10001):
        b = a + (n-1)*d
        p0, p1 = p1, b*p1+p0
        q0, q1 = q1, b*q1+q0
        assert type(p1).__name__ == type(q1).__name__ == 'Integer'
        current = QQ(p1)/q1
        if n > 1:
            lower, upper = sorted((previous, current))
            assert upper-lower == QQ(1)/(q0*q1)
            if upper-lower < threshold:
                return lower, upper, n
        previous = current
    raise ArithmeticError('convergence safety limit exceeded')


class ProgressionFractions(numberdb.Generator):
    table = 'T885'
    parameters = ('a', 'd')
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, height=25):
        for h in range(2, int(height)+1):
            for a in range(1, h):
                yield {'a': a, 'd': h-a}

    def value(self, params, digits):
        lower, upper, _ = convergent_bracket(params['a'], params['d'], digits)
        # CPython Fraction(Sage Rational) can retain method-valued numerator
        # attributes. Convert both integer components explicitly.
        lo = Fraction(int(lower.numerator()), int(lower.denominator()))
        hi = Fraction(int(upper.numerator()), int(upper.denominator()))
        return numberdb.RealInterval(lo, hi)


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    g = ProgressionFractions()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(g.publish())
    elif '--verify' in sys.argv:
        print(g.verify(sample=None))
    else:
        count = 0
        for params in g.enumerate():
            interval = g.value(params, g.digits)
            assert interval.lower < interval.upper
            text = to_text(interval, digits=g.digits)
            assert len(text.replace('0.', '').lstrip('0')) >= 100
            count += 1
        print('Offline exact-enclosure check:', count, 'entries; nothing uploaded.')