backhouse_math.py

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

5518 bytes, as of the version from 2026-12-01 14:15 (current). Recorded here, not run.

"""Certified Backhouse computation; no network or account configuration.

Uses SageMath 10.9 Arb real/complex balls. Global input inequality
p_n < (n+1)^2 is stated by Flajolet (1995), section II. All other bounds
and winding calculations below are explicit. No approximate roots are
trusted as certificates.
"""
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.integer_ring import ZZ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.arith.misc import prime_range
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing


def first_primes(count):
    bound=32
    while True:
        p=list(prime_range(bound))
        if len(p)>=count: return p[:count]
        bound*=2


def tail(N,r):
    """Sum_{n>N} (n+1)^2 r^n, using outward ball operations."""
    return r**(N+1)*((N+2)**2/(1-r)+2*(N+2)*r/(1-r)**2+r*(1+r)/(1-r)**3)


def derivative_tail(N,r):
    """Sum_{n>N} n(n+1)^2 r^(n-1), from sums of k^j r^k."""
    a=N+1
    # n=a+k: n(n+1)^2=n^3+2n^2+n.
    s0=1/(1-r); s1=r/(1-r)**2
    s2=r*(1+r)/(1-r)**3; s3=r*(1+4*r+r*r)/(1-r)**4
    return r**N*((a**3+2*a*a+a)*s0+(3*a*a+4*a+1)*s1+(3*a+2)*s2+s3)


def horner(coeff,z):
    v=z.parent()(0)
    for a in reversed(coeff): v=v*z+a
    return v


def enclose_between(R,a,b):
    return R((a+b)/2).add_error(R((b-a)/2))


def endpoint_record(v):
    """Exact dyadic endpoints, portable without losing ball uncertainty."""
    return [str(QQ(v.lower())),str(QQ(v.upper()))]


def circle_certificate(coeff,N,bits=192,start=64,maxdepth=20,with_tail=True):
    """Enclose whole arcs; compute the winding from endpoint ratios.

    Each whole-arc image lies in a convex rectangle excluding zero.
    Its endpoint chord is homotopic within that rectangle; hence the
    principal endpoint argument increment equals the curve's increment.
    Their sum divided by 2*pi encloses an integer winding number.
    This is an argument-principle zero count including multiplicities.
    """
    R=RealBallField(bits);C=ComplexBallField(bits);rad=R(QQ(3)/4)
    err=tail(N,rad) if with_tail else R(0)
    pi2=2*R.pi(); arcs=[]; increments=[]; minima=[]
    poly=PolynomialRing(C,'z')(coeff); dp=poly.derivative()
    # F(theta)=P_N(R exp(i theta)); |F''| <= sum n^2 p_n R^n.
    m2=horner([n*n*c for n,c in enumerate(coeff)],rad)
    cache={}
    def point(t):
        if t not in cache:
            z=C(0,pi2*R(t)).exp()*rad
            cache[t]=poly(z).add_error(err)
        return cache[t]
    def visit(a,b,depth):
        mid=(a+b)/2;half=pi2*R((b-a)/2)
        z=C(0,pi2*R(mid)).exp()*rad
        center=poly(z);first=C(0,1)*z*dp(z)
        displacement=R(0).add_error(half)
        v=(center+first*displacement).add_error(m2*half*half/2+err)
        if not (v.real().is_finite() and v.imag().is_finite()) or abs(v).lower()<=0:
            if depth>=maxdepth: raise ArithmeticError('Contour unresolved')
            mid=(a+b)/2;visit(a,mid,depth+1);visit(mid,b,depth+1);return
        u=point(a);w=point(b);delta=(w/u).arg()
        assert delta.is_finite() and delta.abs().upper()<R.pi().lower()
        lo=abs(v).lower()
        assert lo>0
        increments.append(delta);minima.append(QQ(lo))
        arcs.append({'a':str(a),'b':str(b), 're':endpoint_record(v.real()),
                     'im':endpoint_record(v.imag()),'delta':endpoint_record(delta)})
    for j in range(start):visit(QQ(j)/start,QQ(j+1)/start,0)
    winding=sum(increments,R(0))/pi2
    low=ZZ(winding.lower().ceil());high=ZZ(winding.upper().floor())
    assert low==high, 'Winding did not isolate one integer'
    return {'radius':'3/4','degree':len(coeff)-1,'truncation':N,
            'with_tail':with_tail,'bits':bits,'arcs':arcs,
            'arc_method':'Centered first-order Taylor enclosure with global finite-polynomial second-derivative bound',
            'second_derivative_bound':endpoint_record(m2),
            'native_polynomial':str(type(poly)),
            'winding_interval':endpoint_record(winding),'zero_count':int(low),
            'minimum_abs_lower':str(min(minima)), 'tail':endpoint_record(err)}


def root_certificate(digits=100):
    R=RealBallField(max(512,numberdb.bits(digits,losing=150)))
    # At |z|<=.687, 1024 terms leave a tail below 10^-160.
    N=max(1024,8*digits+224);ps=first_primes(N);coeff=[ZZ(1)]+ps
    radius=R(QQ(687)/1000);err=tail(N,radius)
    def f(x): return horner(coeff,R(x)).add_error(err)
    a=QQ(-687)/1000;b=QQ(-686)/1000
    fa=f(a);fb=f(b);assert fa<0 and fb>0
    initial={'left':endpoint_record(fa),'right':endpoint_record(fb)}
    # Exact rational bisection, relying only on rigorously decided signs.
    steps=0
    while b-a>QQ(1)/10**(digits+18):
        mid=(a+b)/2;fm=f(mid)
        if fm>0:b=mid
        elif fm<0:a=mid
        else:raise ArithmeticError('Insufficient precision or truncation')
        steps+=1
    s=enclose_between(R,a,b)
    B=-1/s
    assert B.is_finite() and B>1 and QQ(B.rad())<QQ(1)/10**(digits+15)
    dc=[(k+1)*coeff[k+1] for k in range(N)]
    dp=horner(dc,s).add_error(derivative_tail(N,radius))
    assert dp>0
    return B,{'bits':int(R.precision()),'N':N,'primes':[int(x) for x in ps],
        'initial_signs':initial,'bisection_steps':steps,'bracket':[str(a),str(b)],
        'root_ball':endpoint_record(s),'B':endpoint_record(B),
        'derivative':endpoint_record(dp),'root_tail':endpoint_record(err),
        'derivative_tail':endpoint_record(derivative_tail(N,radius))}