check_values.py

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

5915 bytes, as of the version from 2026-12-01 17:23 (current). Recorded here, not run.

"""Independent checks for the Thue-Morse decimal intervals.

Run with SageMath and numberdb installed:
  sage -python check_values.py --input stored.json --output check-results.json
The input may be computation.json (offline) or the read-back stored records.
Only stdlib rational arithmetic and the substitution 0->01, 1->10 are used
for the independent numerical enclosures. No generator code is imported.
"""
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
import argparse
from fractions import Fraction
import json
from pathlib import Path


def decimal_interval(text):
    # Parse the stored spelling exactly, including a significant final zero.
    value = Fraction(text)
    mantissa, _, exponent = text.lower().partition('e')
    places = len(mantissa.partition('.')[2])
    ulp = Fraction(10) ** (int(exponent or '0') - places)
    return value-ulp, value+ulp, ulp


def word_at_least(n):
    word = [0]
    while len(word) < n:
        word = [v for d in word for v in (d, 1-d)]
    return word


def finite_sum(word, b):
    numerator = 0
    for digit in word:
        numerator = b*numerator + digit
    return Fraction(numerator, b**len(word))


def enclosure(b, width_goal, word=None):
    n=1
    while Fraction(1,b**n*(b-1)) >= width_goal:
        n+=1
    if word is None:
        word=word_at_least(n)
    lower=finite_sum(word[:n],b)
    return lower,lower+Fraction(1,b**n*(b-1)),n


def contained(inner, outer):
    return outer[0] < outer[1] and outer[0] <= inner[0] <= inner[1] <= outer[1]


def run(data):
    records=data['entries'];checks=[];failures=[];controls=[]
    prefix='0110100110010110'
    word=word_at_least(1024)
    assert ''.join(map(str,word[:16])) == prefix
    assert word == [n.bit_count()%2 for n in range(len(word))]
    # Known nonzero exact finite sum, plus a known infinite periodic word.
    assert finite_sum([0,1,1,0],2)==Fraction(3,8)
    known=True;negative=True
    # Finite product coefficients from polynomial multiplication, no generator.
    coeff=[1]
    for j in range(10):
        m=2**j; result=coeff+[0]*m
        for k,v in enumerate(coeff): result[k+m]-=v
        coeff=result
    assert coeff==[1-2*d for d in word]
    geometric=[]
    for text, expected in [('01','1/3'),('0110','2/5'),('01101001','7/17'),('0110100110010110','1802/4369')]:
        assert text==''.join(map(str,word[:len(text)]))
        angle=Fraction(int(text,2),2**len(text)-1)
        assert angle==Fraction(expected)
        geometric.append({'periodic_binary_word':text,'angle_in_turns':str(angle),'matches_morphic_prefix':True})
    R=RealBallField(600)
    assert R(QQ(1)/3).is_finite()
    assert not R('nan').is_finite()
    for row in records:
        b=int(row['params']['b']);stored=decimal_interval(str(row['number']))
        independent=enclosure(b,stored[2]/10**25,word)
        ok=contained(independent,stored)
        if not ok:failures.append('digit containment at b=%d'%b)
        # A separately known periodic value exercises weights and tail signs.
        periodic=[n%2 for n in range(independent[2])]
        ps=finite_sum(periodic,b);pt=Fraction(1,b**len(periodic)*(b-1))
        ka=ps<=Fraction(1,b*b-1)<=ps+pt
        known &=ka
        # A(z)=z/(1-z^2)+(1-z)A(z^2), derived by even/odd indices.
        other=enclosure(b*b,stored[2]/(10**25*b))
        func=(Fraction(1,b*b-1)+(b-1)*other[0],Fraction(1,b*b-1)+(b-1)*other[1])
        function_ok=contained(func,stored)
        if not function_ok:failures.append('functional identity at b=%d'%b)
        l,u=independent[:2]
        bad={
          'discard_first_zero':(b*l,b*u),
          'complement_digits':(Fraction(1,b-1)-u,Fraction(1,b-1)-l),
          'omit_product_factor_j0':(Fraction(1,2*(b-1))-(Fraction(1,2*(b-1))-l)*Fraction(b,b-1), Fraction(1,2*(b-1))-(Fraction(1,2*(b-1))-u)*Fraction(b,b-1)),
          'ten_last_place_units':(l+10*stored[2],u+10*stored[2]),
          'vacuous_interval':(Fraction(-10),Fraction(10))}
        rejected={k:not contained(v,stored) for k,v in bad.items()}
        negative &=all(rejected.values())
        controls.append({'b':b,'known_periodic_value':str(Fraction(1,b*b-1)),'known_passed':ka,'negative_rejected':rejected})
        checks.append({'b':b,'stored':row['number'],'stored_ulp':str(stored[2]),'digit_count':independent[2],'digit_lower':str(l),'digit_upper':str(u),'tail_width':str(u-l),'digit_contained':ok,'functional_identity_contained':function_ok})
    assert [int(r['params']['b']) for r in records]==list(range(2,17))
    if not known:failures.append('known answer control failed')
    if not negative:failures.append('negative control accepted')
    return {'checked_entries':len(checks),'total_entries':len(records),'failures':failures,'known_answer_control':known,'negative_control_rejected':negative,'source_prefix_checked':prefix,'morphic_word_vs_bit_parity':len(word),'finite_product_coefficients_checked':len(coeff),'nan_rejected':True,'douady_finite_angle_controls':geometric,'checks':checks,'controls':controls,'skill_manifest_sha256':'b115697c9321b4193a70f8fc1fda7a31aa492fbce8fc08f20b62363d72eab302','independence':'Morphic digit sums and exact rational geometric tails; no generator import or product evaluation is used for the independent decimal enclosures. Shared definitions and source are explicit.'}


if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--input',type=Path,default=Path(__file__).with_name('stored.json') if Path(__file__).with_name('stored.json').exists() else Path(__file__).with_name('computation.json'))
    p.add_argument('--output',type=Path)
    args=p.parse_args();result=run(json.loads(args.input.read_text()))
    if args.output:args.output.write_text(json.dumps(result,indent=2))
    print('CHECK_RESULTS_JSON='+json.dumps(result))
    raise SystemExit(bool(result['failures']))