#!/usr/bin/env python3 """ Math Engine — Exact Arithmetic via GLM Native ALU =================================================== Routes numeric computations through the UBP substrate for exact rational arithmetic with trace and fingerprint. """ from typing import Any, Dict, List, Optional, Tuple from fractions import Fraction import math import time import sys, os _this_dir = os.path.dirname(os.path.abspath(__file__)) _parent = os.path.dirname(_this_dir) if _parent not in sys.path: sys.path.insert(0, _parent) from ubp_unified_v5 import UBPSourceCodeParticlePhysics from .vector_engine import get_pp, classify, word_to_hash24, snap_to_codeword class MathResult: """Result of an exact computation.""" __slots__ = ("operation", "input", "result", "exact_str", "approx", "is_exact", "trace", "fingerprint", "elapsed_us") def __init__(self, operation: str, input_repr: str, result: Any, exact_str: str, approx: float, is_exact: bool, trace: List[str], fingerprint: dict, elapsed_us: int = 0): self.operation = operation self.input = input_repr self.result = result self.exact_str = exact_str self.approx = approx self.is_exact = is_exact self.trace = trace self.fingerprint = fingerprint self.elapsed_us = elapsed_us def to_dict(self) -> dict: return { "operation": self.operation, "input": self.input, "exact": self.exact_str, "approx": self.approx, "is_exact": self.is_exact, "fingerprint": self.fingerprint, "elapsed_us": self.elapsed_us, } class MathEngine: """Exact arithmetic engine grounded in UBP substrate.""" def __init__(self): self.pp = get_pp() def add(self, a, b) -> MathResult: return self._compute("add", f"{a} + {b}", Fraction(a) + Fraction(b)) def subtract(self, a, b) -> MathResult: return self._compute("subtract", f"{a} - {b}", Fraction(a) - Fraction(b)) def multiply(self, a, b) -> MathResult: return self._compute("multiply", f"{a} × {b}", Fraction(a) * Fraction(b)) def divide(self, a, b) -> MathResult: if b == 0: return MathResult("divide", f"{a} / {b}", None, "undefined", float("nan"), False, ["division by zero"], {}) return self._compute("divide", f"{a} / {b}", Fraction(a) / Fraction(b)) def power(self, base, exp) -> MathResult: """Exact integer/rational power.""" b = Fraction(base) e = int(exp) return self._compute("power", f"{base}^{exp}", b ** e) def sqrt_exact(self, n) -> MathResult: """Check if n is a perfect square; return exact or approximate.""" f = Fraction(n) # Check perfect square sqrt_int = int(math.isqrt(int(f))) if sqrt_int * sqrt_int == int(f): return self._compute("sqrt", f"√{n}", Fraction(sqrt_int)) # Not exact approx = float(f) ** 0.5 vec = word_to_hash24(f"sqrt{n}") snapped, _ = snap_to_codeword(vec) fp = classify(snapped) return MathResult("sqrt", f"√{n}", approx, f"√{n} ≈ {approx:.10f}", approx, False, [f"{n} is not a perfect square"], fp) def physics_constant(self, name: str) -> MathResult: """Look up a UBP physics constant.""" constants = { "Y": self.pp.Y, "Y_INV": Fraction(1) / self.pp.Y, "wobble": self.pp.wobble, "L": self.pp.L, "L_s": self.pp.L_s, "sigma": self.pp.sigma, "U_e": Fraction(self.pp.U_e), "monad": self.pp.monad, "pi": self.pp.pi, "phi": self.pp.phi, "e": self.pp.e_const, } if name not in constants: return MathResult("constant", name, None, "unknown", float("nan"), False, [f"Unknown constant: {name}"], {}) val = constants[name] return self._compute("constant", name, val) def muon_ratio(self) -> MathResult: """Compute m_μ/m_e using UBP formula: 169/w""" w = self.pp.wobble result = Fraction(169) / w target = Fraction(2067683, 10000) err = abs(float(result) - float(target)) / float(target) * 100 m = self._compute("muon_ratio", "169/w", result) m.fingerprint["target_error_pct"] = float(err) m.fingerprint["verdict"] = "PREDICTIVE" if err < 0.1 else "SURPRISING" if err < 1 else "PROVISIONAL" return m def alpha_s(self) -> MathResult: """Compute α_s using UBP formula: 24·Y⁴""" Y = self.pp.Y result = 24 * Y**4 target = Fraction(1181, 10000) err = abs(float(result) - float(target)) / float(target) * 100 m = self._compute("alpha_s", "24·Y⁴", result) m.fingerprint["target_error_pct"] = float(err) m.fingerprint["verdict"] = "PREDICTIVE" if err < 0.1 else "SURPRISING" if err < 1 else "PROVISIONAL" return m def hubble(self) -> MathResult: """Compute H₀ using UBP formula: (1/3)·w·Y³·U_e""" w = self.pp.wobble Y = self.pp.Y Ue = Fraction(self.pp.U_e) result = Fraction(1, 3) * w * Y**3 * Ue target = Fraction(70) err = abs(float(result) - float(target)) / float(target) * 100 m = self._compute("H0", "(1/3)·w·Y³·U_e", result) m.fingerprint["target_error_pct"] = float(err) m.fingerprint["verdict"] = "PREDICTIVE" if err < 0.1 else "SURPRISING" if err < 1 else "PROVISIONAL" return m def _compute(self, operation: str, input_repr: str, result: Fraction) -> MathResult: """Core computation with substrate fingerprinting.""" t0 = time.perf_counter_ns() exact_str = str(result) approx = float(result) is_exact = True trace = [f"Operation: {operation}", f"Input: {input_repr}", f"Result (Fraction): {result}", f"Result (float): {approx}"] # Fingerprint: classify the result's magnitude in the substrate # Use the integer part to get a 24-bit vector int_part = abs(int(result)) if result.denominator == 1 else abs(int(result * 1000)) int_part = int_part % (2**24) # fit in 24 bits vec = [(int_part >> (23 - i)) & 1 for i in range(24)] snapped, _ = snap_to_codeword(vec) fingerprint = classify(snapped) elapsed = int((time.perf_counter_ns() - t0) / 1000) return MathResult(operation, input_repr, result, exact_str, approx, is_exact, trace, fingerprint, elapsed)