checks.py

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

9056 bytes, as of the version from 2026-12-01 03:06 (current). Recorded here, not run.

"""Check inverse-li values using a bounded convergent series and PV quadrature.

sage -python checks.py   (requires SageMath/Arb, numberdb, mpmath)
Place entries.json, the flat list of parameter/number records, beside this file.
The program prints NUMBERDB_CHECKS_JSON with all numerical evidence. Endpoint
certification uses no generator and never calls Arb Ei. Gamma/log ball
primitives are shared. mpmath root and regularized PV quadrature comparisons
use another implementation but are not rigorous error certificates.
The PV component is reused from the documented family computation component;
its source and SHA-256 are in research.md. A sibling table is no evidence.
"""
import json,sys,platform,importlib.metadata
from pathlib import Path
from fractions import Fraction
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.env import SAGE_VERSION
import mpmath as mp
HERE=Path(__file__).resolve().parent


def rational(text):
    f=Fraction(str(text));return QQ(f.numerator)/f.denominator


def written(text):
    center=rational(text)
    # All this table's values are ordinary fixed-point positive decimals.
    assert '.' in text and 'e' not in text.lower()
    ulp=QQ(1)/10**len(text.split('.')[1])
    return center,ulp


def ei_series(r, decimal_digits=210):
    """DLMF 6.6.1 with a positive geometric tail after t_k=r^k/(k*k!).

    For j>=k+1, t_(j+1)/t_j = r*j/(j+1)^2 <= upper(r)/(k+1)=q.
    Once q<1, the omitted tail is at most upper(t_(k+1))/(1-q).
    All rounding, gamma and logarithm errors propagate in Arb balls.
    """
    R=r.parent();assert r.is_finite() and r>0
    hi=r.upper().exact_rational();term=r;total=R(0);k=1
    threshold=QQ(1)/10**(decimal_digits+25)
    while True:
        total+=term
        nxt=term*r*k/(k+1)**2
        q=hi/(k+1)
        if q<1:
            tail=nxt.upper().exact_rational()/(1-q)
            if tail<threshold:break
        term=nxt;k+=1
    result=R.euler_constant()+r.log()+total+R(0).union(R(tail))
    assert result.is_finite()
    return result,{'terms':k,'q_upper':str(R(q)),'tail_bound':str(R(tail)),
                   'radius':str(result.rad())}


def certify(text,x):
    R=RealBallField(896);center,ulp=written(text)
    low,high=center-ulp,center+ulp
    assert low>1 and high>low and high-low==2*ulp
    left,el=ei_series(R(low).log());left-=x
    right,er=ei_series(R(high).log());right-=x
    assert left.rad().exact_rational()<ulp/10**100
    assert right.rad().exact_rational()<ulp/10**100
    return bool(left<0 and right>0),{'x':str(x),'number':text,'ulp':str(ulp),
      'left_residual':str(left),'right_residual':str(right),
      'left_series':el,'right_series':er}

# Exact coefficients of 1/log(1+z)-1/z, through z^30. This local expansion
# is used only for numerical quadrature where |z|<1e-10. Its omitted terms
# are far below the 200-digit quadrature comparison scale; no rigorous
# quadrature certification is claimed.
b=[QQ(1)]
for n in range(1,32):
    b.append(-sum(((-1)**j*QQ(1)/(j+1))*b[n-j] for j in range(1,n+1)))

def pv_li(y):
    coeff=[mp.mpf(str(c.numerator()))/int(c.denominator()) for c in b[1:]]
    def h(t):
        if t==0:return mp.mpf(1)
        z=t-1
        if abs(z)<mp.mpf('1e-10'):
            return mp.polyval(list(reversed(coeff)),z)
        return 1/mp.log(t)-1/z
    # For 0<t<1/2, t=exp(-u) resolves the logarithmic endpoint.
    def lower_integrand(u):
        if mp.isinf(u):return mp.mpf(0)
        t=mp.exp(-u)
        return t*(-1/u+1/(-mp.expm1(-u)))
    lower=mp.quad(lower_integrand,[mp.log(2),1,2,4,8,16,32,64,128,256,512,1024,mp.inf])
    points=[mp.mpf('0.5'),mp.mpf('0.9'),mp.mpf(1),mp.mpf('1.1'),y]
    points=sorted(set(p for p in points if p<=y))
    return mp.log(y-1)+lower+mp.quad(h,points)

def run():
    rows=json.loads((HERE/'entries.json').read_text())
    assert [int(r['params']['x']) for r in rows]==list(range(1,501))
    R=RealBallField(896);certificates=[];prev=None;negative_controls=[]
    for row in rows:
        n=int(row['params']['x']);text=row['number'];center,ulp=written(text)
        okay,cert=certify(text,QQ(n));assert okay,(n,cert)
        if prev is not None:assert center-ulp>prev
        prev=center+ulp;certificates.append(cert)
        if n in (1,2,10,100,500):
            shifted=center+4*ulp
            left,_=ei_series(R(shifted-ulp).log());right,_=ei_series(R(shifted+ulp).log())
            rejected=not(left-n<0 and right-n>0);assert rejected
            # An off-by-one index also must not certify the written interval.
            wrong_index,_=certify(text,QQ(n+1));assert not wrong_index
            negative_controls.append({'x':n,'shift_ulp':4,'shift_rejected':True,'index_plus_one_rejected':True})
    # Nonzero checker control: Ei(1) computed as gamma+integral(expm1(t)/t).
    one,one_evidence=ei_series(R(1))
    assert one.is_finite() and one>1 and one.rad().exact_rational()<QQ(1)/10**230
    assert not R('nan').is_finite()
    assert R(0).union(R(10000)).rad().exact_rational()>1
    comparisons=[];quadratures=[]
    for dps in (150,200):
        with mp.workdps(dps+45):
            worst=mp.mpf(0);worst_n=None;largest_residual=mp.mpf(0);sample=[]
            for row in rows:
                n=int(row['params']['x']);text=row['number'];c=mp.mpf(text)
                unit=mp.mpf(1)/10**len(text.split('.')[1])
                root=mp.findroot(lambda r:mp.ei(r)-n,mp.log(c))
                y=mp.exp(root);distance=abs(y-c)/unit
                assert distance<1
                if distance>worst:worst=distance;worst_n=n
                residual=abs(mp.ei(mp.log(c))-n)
                largest_residual=max(largest_residual,residual)
                if n in (1,2,10,100,500):sample.append({'x':n,'value':mp.nstr(y,dps),'distance_ulp':mp.nstr(distance,20)})
            comparisons.append({'dps':dps,'working_dps':dps+45,'entries':len(rows),
               'max_distance_ulp':mp.nstr(worst,25),'max_at_x':worst_n,
               'max_center_composition_residual':mp.nstr(largest_residual,20),'samples':sample})
            expected_e=mp.euler+mp.quad(lambda t:mp.expm1(t)/t if t else mp.mpf(1),[0,1])
            one_center=mp.mpf(str(one.mid()))
            assert abs(one_center-expected_e)<mp.mpf(10)**(-dps)
            at_e=pv_li(mp.e);at_two=pv_li(mp.mpf(2));expected_two=mp.ei(mp.log(2))
            tolerance=mp.mpf(10)**(-dps+10)
            assert abs(at_e-expected_e)<tolerance and at_e>1
            assert abs(at_two-expected_two)<tolerance and at_two>1
            tests=[]
            for n in (1,2,10,100,500):
                text=rows[n-1]['number'];center=mp.mpf(text);unit=mp.mpf(1)/10**len(text.split('.')[1])
                pv=pv_li(center);residual=pv-n
                assert abs(residual)<4*unit/mp.log(center)+tolerance
                assert abs(residual-at_two)>1 # rejects the offset normalization
                tests.append({'x':n,'PV_li_center':mp.nstr(pv,120),'residual':mp.nstr(residual,25),'wrong_offset_residual':mp.nstr(residual-at_two,25)})
            r0=mp.findroot(mp.ei,(mp.mpf('0.25'),mp.mpf('0.5')));mu=mp.exp(r0)
            pv_mu=pv_li(mu);assert abs(pv_mu)<tolerance
            compositions=[]
            for y in (mp.mpf(2),mp.e,mp.e**2):
                independently_computed_input=pv_li(y)
                recovered=mp.exp(mp.findroot(lambda r:mp.ei(r)-independently_computed_input,mp.log(y)))
                err=abs(recovered-y);assert err<tolerance
                compositions.append({'y':mp.nstr(y,25),'PV_input':mp.nstr(independently_computed_input,30),'inverse_composition_error':mp.nstr(err,20)})
            quadratures.append({'dps':dps,'working_dps':dps+45,'PV_e':mp.nstr(at_e,35),'PV_e_error':mp.nstr(at_e-expected_e,20),
                'PV_2':mp.nstr(at_two,35),'PV_2_error':mp.nstr(at_two-expected_two,20),
                'mu':mp.nstr(mu,110),'PV_mu':mp.nstr(pv_mu,20),'tests':tests,'inverse_compositions':compositions})
    versions={'SageMath':SAGE_VERSION,'python':platform.python_version(),'numberdb':numberdb.__version__,'mpmath':mp.__version__}
    for d in importlib.metadata.distributions():
        name=d.metadata.get('Name','')
        if 'flint' in name.lower() or 'arb' in name.lower():versions[name]=d.version
    result={'checked_entries':len(rows),'total_entries':len(rows),'failures':[],
      'known_answer_control':True,'negative_control_rejected':True,'series_bits':896,
      'series_certificates':certificates,'negative_controls':negative_controls,
      'Ei_one':str(one),'Ei_one_series':one_evidence,'comparisons':comparisons,'PV_checks':quadratures,
      'versions':versions,'skill_manifest':'../20261201T025022Z-build-skills/manifest.json',
      'independence':'Bounded DLMF series replaces Arb Ei, sharing only gamma/log primitives; mpmath and the regularized PV integral add separate implementation/normalization comparisons. These are builder checks, not an independent actor verdict.'}
    print('NUMBERDB_CHECKS_JSON='+json.dumps(result))

if __name__=='__main__':run()