"""Checked approximate roots of exact nonnegative rational squared distances.""" from decimal import ( Context, Decimal, DivisionByZero, InvalidOperation, MAX_EMAX, MIN_EMIN, Overflow, ROUND_HALF_EVEN, localcontext, ) from fractions import Fraction import math def sqrt_rational(squared): """Return a float approximation, rejecting positive roots rounded to zero/inf. Exact squared values remain authoritative. The 80-digit intermediate avoids converting the square to binary64 before taking its root; this is not a guarantee of correctly rounded binary64 results for every rational input. """ if isinstance(squared, bool) or not isinstance(squared, (int, Fraction)): raise TypeError("Squared distance must be an int or Fraction") squared = Fraction(squared) if squared < 0: raise ValueError("Squared distance must be nonnegative") if not squared: return 0.0 # Do not inherit the caller's precision, exponent limits, flags or traps. context = Context(prec=80, rounding=ROUND_HALF_EVEN, Emin=MIN_EMIN, Emax=MAX_EMAX, traps=[InvalidOperation, DivisionByZero, Overflow]) with localcontext(context): root = (Decimal(squared.numerator) / Decimal(squared.denominator)).sqrt() result = float(root) if not math.isfinite(result) or result == 0: raise ValueError("Positive RMS is outside finite nonzero float display range; use the exact squared value") return result