"""Rational intervals for the scalar estimates. No binary floating point.""" from dataclasses import dataclass from fractions import Fraction from functools import lru_cache from math import isqrt Q = Fraction GRID = 10**30 def floor_q(x): return x.numerator // x.denominator def ceil_q(x): return -floor_q(-x) @dataclass(frozen=True) class Interval: lo: Q hi: Q def __post_init__(self): if self.lo > self.hi: raise ValueError("unordered endpoints") def __add__(self, other): b = box(other) return Interval(self.lo + b.lo, self.hi + b.hi) __radd__ = __add__ def __neg__(self): return Interval(-self.hi, -self.lo) def __sub__(self, other): return self + (-box(other)) def __rsub__(self, other): return box(other) - self def __mul__(self, other): b = box(other) products = [x*y for x in (self.lo, self.hi) for y in (b.lo, b.hi)] return Interval(min(products), max(products)) __rmul__ = __mul__ def __truediv__(self, other): b = box(other) if b.lo <= 0 <= b.hi: raise ZeroDivisionError("interval contains zero") return self * Interval(1/b.hi, 1/b.lo) def __rtruediv__(self, other): return box(other) / self def __pow__(self, n): if not isinstance(n, int) or n < 0 or self.lo < 0: raise ValueError("power requires a nonnegative interval and exponent") return Interval(self.lo**n, self.hi**n) def box(x): if isinstance(x, Interval): return x if isinstance(x, float): raise TypeError("binary floating-point inputs are forbidden") return Interval(Q(x), Q(x)) def hull(x, y): return Interval(box(x).lo, box(y).hi) def compact(a, b): return Interval(Q(floor_q(a*GRID), GRID), Q(ceil_q(b*GRID), GRID)) def sqrt(x): b = box(x) if b.lo < 0: raise ValueError("negative square root") lower = isqrt(floor_q(b.lo * GRID**2)) upper = isqrt(floor_q(b.hi * GRID**2)) if Q(upper**2, GRID**2) < b.hi: upper += 1 return Interval(Q(lower, GRID), Q(upper, GRID)) def log_reduced(x): """For 1 <= x <= 2, the remaining atanh series is a geometric majorant.""" if not 1 <= x <= 2: raise ValueError("argument outside reduced interval") z = (x-1)/(x+1) term = z total = Q(0) for j in range(36): total += term/(2*j+1) term *= z*z return compact(2*total, 2*(total + term/(73*(1-z*z)))) LOG2 = log_reduced(Q(2)) @lru_cache(maxsize=1024) def log_point(x): if x <= 0: raise ValueError("logarithm requires a positive argument") k = x.numerator.bit_length() - x.denominator.bit_length() y = x / (Q(2)**k) if y < 1: y *= 2 k -= 1 value = log_reduced(y) + k*LOG2 return compact(value.lo, value.hi) def ln(x): b = box(x) return Interval(log_point(b.lo).lo, log_point(b.hi).hi) def atan_inverse(n): """Two consecutive partial sums enclose arctan(1/n).""" x = Q(1, n) term = x total = Q(0) for j in range(24): total += term/(2*j+1) term *= -x*x nxt = total + term/49 return compact(min(nxt, total), max(nxt, total)) PI = 16*atan_inverse(5) - 4*atan_inverse(239) # Machin's identity def fixed(q, places, upper): scale = 10**places n = ceil_q(q*scale) if upper else floor_q(q*scale) sign = "-" if n < 0 else "" a, b = divmod(abs(n), scale) if places == 0: return sign + str(a) return f"{sign}{a}.{b:0{places}d}"