#!/usr/bin/env python3
"""N03 — arithmetic from D1287 supplied sources.
No network, external packages, fitting operations or shared runtime files.
Printed source cells and unrounded arithmetic are distinct outputs.
"""

import math
from decimal import Decimal, ROUND_HALF_UP, getcontext
from fractions import Fraction

getcontext().prec = 40
PHI = (1.0 + math.sqrt(5.0)) / 2.0

# Exact arithmetic in Q(phi), with phi^2=phi+1. A pair is a+b*phi.
def qmul(x, y):
    a, b = x
    c, d = y
    return (a*c + b*d, a*d + b*c + b*d)


def qadd(x, y):
    return (x[0]+y[0], x[1]+y[1])


def qstr(x):
    return str(x[0]) + " + (" + str(x[1]) + ")*phi"

def main():
    print('=== row 3 ===')
    print('Scorecard (verbatim): DET-7 det(Gram) = 7 theory 7 experiment structural deviation — Structural input —')
    phi = (Fraction(0), Fraction(1))
    inv = (Fraction(-1), Fraction(1))
    s = qadd(qadd(qmul(phi,phi), (Fraction(1),Fraction(0))), qmul(inv,inv))
    det = qadd(qmul(s,s), (Fraction(-9),Fraction(0)))
    assert s == (Fraction(4),Fraction(0))
    assert det == (Fraction(7),Fraction(0))
    print("s = " + qstr(s))
    print("gram_diagonal = 4; gram_off_diagonal = 3")
    print("det_Gram = 4*4 - 3*3 = 7")
    print("theory = 7; comparator = structural (not a measurement)")
    print("signed_percent = NOT APPLICABLE; d = NOT APPLICABLE")
    print()


if __name__ == "__main__":
    main()
