generate.py

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

6372 bytes, as of the version from 2026-11-15 19:16 (current). Recorded here, not run.

"""T717: harmonic inverse central-binomial sums.

Requires SageMath (including symbolic initialization and Arb).
Install the Python client in that Sage environment first:
  sage -pip install numberdb
  sage -python generate.py              # compute, no website write
  sage -python generate.py --verify     # reproduce all stored entries
  sage -python generate.py --publish    # additive update of this table

See certification.md for the explicit geometric and endpoint error bounds.
The default selection is weight s+r <= 6, u=-1,1,2,3 and u=4 if s>=2.
All arguments are exact integers/rationals; (r) is harmonic order, not a power.
At u=4 a finite Stirling/EM expansion is summed with Hurwitz zeta, including
an explicit global remainder. This is not an unbounded asymptotic evaluation.
No credentials or model provenance are embedded in this reusable source.
"""
import functools
import math
import os
import sys
import numberdb.sage as numberdb
from sage.symbolic.ring import SR
from sage.arith.misc import bernoulli
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.power_series_ring import PowerSeriesRing


def selection():
    for weight in range(2, 7):
        for s in range(1, weight):
            r = weight-s
            for u in (-1, 1, 2, 3, 4):
                if u != 4 or s >= 2:
                    yield {'s': s, 'r': r, 'u': u}


@functools.lru_cache(None)
def coefficients(K, M):
    S = PowerSeriesRing(QQ, 'x', default_prec=K)
    x = S.gen()
    L = sum((2-QQ(2)**(1-2*k))*bernoulli(2*k)*x**(2*k-1)
            / (2*k*(2*k-1)) for k in range(1, M+1))
    P = L.exp()
    return tuple(L[j] for j in range(K)), tuple(P[j] for j in range(K))


@functools.lru_cache(None)
def zeta_tail(twice_p, N, bits, derivative=False):
    R = RealBallField(bits)
    p = QQ(twice_p)/2
    if not derivative:
        return R(p).zeta(N)
    C = ComplexBallField(bits)
    pol = PolynomialRing(C, 't')
    f = (pol.gen()+C(p))._zeta_series(2, a=N)
    assert f[1].imag().is_zero()
    return -f[1].real()   # sum log(n)/n^p


def direct(s, r, u, digits):
    R = RealBallField(numberdb.bits(digits, losing=200))
    q = R(abs(u))/4
    if q.is_zero():
        return R(0)
    N = 8
    target = R(10)**(-digits-35)
    def tail(n):
        return q**n*((2*n+1)/(1-q)+2*q/(1-q)**2)
    while not tail(N) < target:
        N += 16
    H, invbin, upow, total = R(0), R(1), R(1), R(0)
    for n in range(1, N):
        invbin *= R(n)/(2*(2*n-1))
        upow *= R(u)
        total += upow*invbin*H/R(n)**s
        H += R(n)**(-r)
    return total.add_error(tail(N))


def endpoint(s, r, digits):
    if s < 2:
        raise ValueError('The absolutely convergent endpoint requires s >= 2')
    bits = numberdb.bits(digits, losing=220)
    R = RealBallField(bits)
    # Scale truncation and N for requested digits; defaults K=128,M=64,N=256.
    K = max(128, int(math.ceil((digits+45)/1.15)))
    K += K % 2
    M = K//2
    N = max(256, 2*K)
    rho = QQ(1)/(max(16, (K+7)//8))
    L, Pq = coefficients(K, M)
    P = [R(c) for c in Pq]
    p = QQ(2*s-1)/2
    h = [R(0)]*(r+2*M)
    if r == 1:
        h[0] = R.euler_constant()
        h[1] = -R(1)/2
        for k in range(1, M+1):
            h[2*k] = -R(bernoulli(2*k))/(2*k)
        herror = abs(R(bernoulli(2*M+2))/(2*M+2))*R(N)**(-2*M-2)
    else:
        h[0] = R(r).zeta()
        h[r-1] = -R(1)/(r-1)
        h[r] = -R(1)/2
        for k in range(1, M+1):
            rising = math.prod(range(r, r+2*k-1))
            h[r+2*k-1] = -R(bernoulli(2*k)*QQ(rising)/math.factorial(2*k))
        herror = abs(h[r+2*M-1])*R(N)**(-(r+2*M-1))
    product = [R(0)]*(len(P)+len(h)-1)
    for j, a in enumerate(P):
        for k, b in enumerate(h):
            product[j+k] += a*b
    tail_sum = sum(c*zeta_tail(int(2*p)+2*j, N, bits)
                   for j,c in enumerate(product) if not c.is_zero())
    if r == 1:
        tail_sum += sum(c*zeta_tail(int(2*p)+2*j, N, bits, True)
                        for j,c in enumerate(P) if not c.is_zero())
    # First neglected log-Gamma terms, bounded separately before subtraction.
    m = 2*M+1
    d = R((2+QQ(2)**(-m))*abs(bernoulli(2*M+2))/((2*M+2)*m))
    logerr = d*R(N)**(-m)
    LabsN = sum(abs(R(c))*R(N)**(-j) for j,c in enumerate(L))
    Erho = sum(abs(R(c))*R(rho)**j for j,c in enumerate(L)).exp()
    ratio = R(1)/(N*R(rho))
    assert ratio < 1
    Eerror = Erho*ratio**K/(1-ratio) + (LabsN+logerr).exp()*logerr
    Pbound = Erho/(1-ratio)
    # H_(n-1)^(r) <= 1+log(n); integral test for this decreasing majorant.
    NN, pp = R(N), R(p)
    Jlog = NN**(-pp)*(1+NN.log()) + NN**(1-pp)*((1+NN.log())/(pp-1)+1/(pp-1)**2)
    J0 = NN**(-pp)+NN**(1-pp)/(pp-1)
    error = R.pi().sqrt()*(Eerror*Jlog+Pbound*herror*J0)
    H, ratio4, total = R(0), R(1), R(0)
    for n in range(1, N):
        ratio4 *= R(2*n)/(2*n-1)
        total += ratio4*H/R(n)**s
        H += R(n)**(-r)
    result = total + R.pi().sqrt()*tail_sum
    result = result.add_error(error)
    assert result.is_finite() and result.accuracy() > numberdb.bits(digits+5)
    return result


class HarmonicInverse(numberdb.Generator):
    table = os.environ.get('NUMBERDB_TABLE', 'T717')
    parameters = ['s', 'r', 'u']
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, limit=None):
        yield from selection()

    def value(self, params, digits):
        s, r, u = int(params['s']), int(params['r']), QQ(params['u'])
        if s < 1 or r < 1 or abs(u) > 4:
            raise ValueError('Outside the defined domain')
        if u == 4:
            return endpoint(s, r, digits)
        if u == -4:
            raise ValueError('Negative endpoint is not implemented by this generator')
        return direct(s, r, u, digits)


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    g = HarmonicInverse()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        g.publish()
    elif '--verify' in sys.argv:
        g.verify(sample=None)
    else:
        for params in g.enumerate():
            value = g.value(params, g.digits)
            print(params, value)