#!/usr/bin/env python3 """Minimal rigorous interval arithmetic on numpy arrays (float64, outward rounding by one ulp after every operation), with verified sin / cos (Taylor polynomial with exact-rational coefficient enclosures and explicit remainder) and second-order jets (value, gradient, Hessian) in two variables (r, t). Rigour rests on: IEEE-754 round-to-nearest for + - * / on float64 (true result within half an ulp of the computed one, so widening by one ulp with nextafter encloses it), exact rational arithmetic (fractions.Fraction) for constants. No library sin/cos/pi is trusted. """ import math from fractions import Fraction import numpy as np INF = np.inf def dn(x): return np.nextafter(x, -INF) def up(x): return np.nextafter(x, INF) class I: """closed interval [lo, hi] (arrays broadcast)""" __slots__ = ('lo', 'hi') def __init__(self, lo, hi=None): self.lo = np.asarray(lo, dtype=np.float64) self.hi = self.lo if hi is None else np.asarray(hi, dtype=np.float64) def iadd(a, b): return I(dn(a.lo + b.lo), up(a.hi + b.hi)) def isub(a, b): return I(dn(a.lo - b.hi), up(a.hi - b.lo)) def ineg(a): return I(-a.hi, -a.lo) def imul(a, b): p1 = a.lo * b.lo; p2 = a.lo * b.hi; p3 = a.hi * b.lo; p4 = a.hi * b.hi return I(dn(np.minimum(np.minimum(p1, p2), np.minimum(p3, p4))), up(np.maximum(np.maximum(p1, p2), np.maximum(p3, p4)))) def isqr(a): l2 = a.lo * a.lo; h2 = a.hi * a.hi mx = np.maximum(l2, h2) mn = np.where((a.lo <= 0) & (a.hi >= 0), 0.0, np.minimum(l2, h2)) return I(np.maximum(dn(mn), 0.0), up(mx)) def iinv(a): if not np.all(a.lo > 0): raise ZeroDivisionError("iinv: interval not strictly positive") return I(dn(1.0 / a.hi), up(1.0 / a.lo)) def ihull(a, b): return I(np.minimum(a.lo, b.lo), np.maximum(a.hi, b.hi)) def iscale(a, c): """multiply by an exact float constant c""" return imul(a, I(float(c))) def frac_enclosure(fr): """floats lo <= fr <= hi for an exact Fraction (verified by exact comparison)""" x = float(fr) lo = hi = x while Fraction(lo) > fr: lo = math.nextafter(lo, -math.inf) while Fraction(hi) < fr: hi = math.nextafter(hi, math.inf) return lo, hi def _pi_bounds(): """exact rational bounds for pi from Machin's formula pi = 16 atan(1/5) - 4 atan(1/239) (alternating series)""" def atan_bounds(n, terms): s = Fraction(0) for j in range(terms): # terms even: partial sum with an even number of terms is a lower bound s += Fraction((-1) ** j, (2 * j + 1) * n ** (2 * j + 1)) return s, s + Fraction(1, (2 * terms + 1) * n ** (2 * terms + 1)) a_lo, a_hi = atan_bounds(5, 30) b_lo, b_hi = atan_bounds(239, 12) return 16 * a_lo - 4 * b_hi, 16 * a_hi - 4 * b_lo _PL, _PH = _pi_bounds() PI_LO = math.nextafter(float(_PL), -math.inf) while Fraction(PI_LO) > _PL: PI_LO = math.nextafter(PI_LO, -math.inf) PI_HI = math.nextafter(float(_PH), math.inf) while Fraction(PI_HI) < _PH: PI_HI = math.nextafter(PI_HI, math.inf) assert Fraction(PI_LO) < _PL and _PH < Fraction(PI_HI) and PI_HI - PI_LO < 2e-15 PI = I(PI_LO, PI_HI) PIH = I(dn(PI_LO / 2), up(PI_HI / 2)) # pi/2 XMAX = 5.0 NT = 21 _CS = [frac_enclosure(Fraction((-1) ** j, math.factorial(2 * j + 1))) for j in range(NT + 1)] _CC = [frac_enclosure(Fraction((-1) ** j, math.factorial(2 * j))) for j in range(NT + 1)] _REM_S = frac_enclosure(Fraction(5) ** (2 * NT + 3) / math.factorial(2 * NT + 3))[1] _REM_C = frac_enclosure(Fraction(5) ** (2 * NT + 2) / math.factorial(2 * NT + 2))[1] assert _REM_S < 1e-20 and _REM_C < 1e-20 def _taylor(x): """enclosures of sin and cos over the interval x (|x| <= XMAX); tight when x is thin""" if not (np.all(x.lo >= -XMAX) and np.all(x.hi <= XMAX)): raise ValueError("sin/cos argument out of the verified range") y = isqr(x) ps = I(_CS[NT][0], _CS[NT][1]); pc = I(_CC[NT][0], _CC[NT][1]) for j in range(NT - 1, -1, -1): ps = iadd(imul(ps, y), I(_CS[j][0], _CS[j][1])) pc = iadd(imul(pc, y), I(_CC[j][0], _CC[j][1])) s = imul(x, ps) s = I(np.maximum(dn(s.lo - _REM_S), -1.0), np.minimum(up(s.hi + _REM_S), 1.0)) c = I(np.maximum(dn(pc.lo - _REM_C), -1.0), np.minimum(up(pc.hi + _REM_C), 1.0)) return s, c def _crit(mult): """enclosure of mult * pi/2 for a small integer mult""" return imul(PIH, I(float(mult))) def isincos(x): """range enclosures of sin and cos over x""" sl, cl = _taylor(I(x.lo)); sh, ch = _taylor(I(x.hi)) slo = np.minimum(sl.lo, sh.lo); shi = np.maximum(sl.hi, sh.hi) clo = np.minimum(cl.lo, ch.lo); chi = np.maximum(cl.hi, ch.hi) for mult, kind in ((1, 'smax'), (-3, 'smax'), (-1, 'smin'), (3, 'smin'), (0, 'cmax'), (2, 'cmin'), (-2, 'cmin')): c = _crit(mult) has = (x.lo <= c.hi) & (x.hi >= c.lo) if kind == 'smax': shi = np.where(has, 1.0, shi) elif kind == 'smin': slo = np.where(has, -1.0, slo) elif kind == 'cmax': chi = np.where(has, 1.0, chi) else: clo = np.where(has, -1.0, clo) return I(slo, shi), I(clo, chi) # --------------------------------------------------------------------------------------------------------------- # second-order jets in (r, t) ZERO = I(0.0) class Jet: __slots__ = ('v', 'r', 't', 'rr', 'rt', 'tt') def __init__(self, v, r=ZERO, t=ZERO, rr=ZERO, rt=ZERO, tt=ZERO): self.v, self.r, self.t, self.rr, self.rt, self.tt = v, r, t, rr, rt, tt def _isz(a): return a is ZERO def _a(a, b): if _isz(a): return b if _isz(b): return a return iadd(a, b) def _m(a, b): if _isz(a) or _isz(b): return ZERO return imul(a, b) def _two(a): return ZERO if _isz(a) else imul(a, I(2.0)) def add(a, b): if isinstance(a, Jet): return Jet(_a(a.v, b.v), _a(a.r, b.r), _a(a.t, b.t), _a(a.rr, b.rr), _a(a.rt, b.rt), _a(a.tt, b.tt)) return iadd(a, b) def sub(a, b): if isinstance(a, Jet): n = lambda z: ZERO if _isz(z) else ineg(z) return add(a, Jet(n(b.v), n(b.r), n(b.t), n(b.rr), n(b.rt), n(b.tt))) return isub(a, b) def mul(a, b): if isinstance(a, Jet): return Jet(_m(a.v, b.v), _a(_m(a.r, b.v), _m(a.v, b.r)), _a(_m(a.t, b.v), _m(a.v, b.t)), _a(_a(_m(a.rr, b.v), _two(_m(a.r, b.r))), _m(a.v, b.rr)), _a(_a(_m(a.rt, b.v), _m(a.r, b.t)), _a(_m(a.t, b.r), _m(a.v, b.rt))), _a(_a(_m(a.tt, b.v), _two(_m(a.t, b.t))), _m(a.v, b.tt))) return imul(a, b) def _sq(a): return ZERO if _isz(a) else isqr(a) def sqr(a): if isinstance(a, Jet): return Jet(isqr(a.v), _two(_m(a.v, a.r)), _two(_m(a.v, a.t)), _two(_a(_sq(a.r), _m(a.v, a.rr))), _two(_a(_m(a.r, a.t), _m(a.v, a.rt))), _two(_a(_sq(a.t), _m(a.v, a.tt)))) return isqr(a) def _compose(a, h, hp, hpp): return Jet(h, _m(hp, a.r), _m(hp, a.t), _a(_m(hpp, _sq(a.r)), _m(hp, a.rr)), _a(_m(hpp, _m(a.r, a.t)), _m(hp, a.rt)), _a(_m(hpp, _sq(a.t)), _m(hp, a.tt))) def sin(a): if isinstance(a, Jet): s, c = isincos(a.v) return _compose(a, s, c, ineg(s)) return isincos(a)[0] def cos(a): if isinstance(a, Jet): s, c = isincos(a.v) return _compose(a, c, ineg(s), ineg(c)) return isincos(a)[1] def inv(a): if isinstance(a, Jet): h = iinv(a.v) h2 = isqr(h) return _compose(a, h, ineg(h2), imul(I(2.0), imul(h2, h))) return iinv(a) def scale(a, c): cI = I(float(c)) if isinstance(a, Jet): f = lambda z: ZERO if _isz(z) else imul(z, cI) return Jet(f(a.v), f(a.r), f(a.t), f(a.rr), f(a.rt), f(a.tt)) return imul(a, cI) def selftest(): rng = np.random.default_rng(1) x = rng.uniform(-4.9, 4.9, 20000) s, c = isincos(I(x)) assert np.all(s.lo <= np.sin(x) + 1e-15) and np.all(s.hi >= np.sin(x) - 1e-15) assert np.all(c.lo <= np.cos(x) + 1e-15) and np.all(c.hi >= np.cos(x) - 1e-15) wid = max(float(np.max(s.hi - s.lo)), float(np.max(c.hi - c.lo))) # ranges a = rng.uniform(-4.9, 4.4, 2000); b = a + rng.uniform(0, 0.5, 2000) s, c = isincos(I(a, b)) for j in range(0, 2000, 7): xx = np.linspace(a[j], b[j], 201) assert s.lo[j] <= np.sin(xx).min() + 1e-15 and s.hi[j] >= np.sin(xx).max() - 1e-15 assert c.lo[j] <= np.cos(xx).min() + 1e-15 and c.hi[j] >= np.cos(xx).max() - 1e-15 # jets against finite differences of a test function F = sin(r t) / (1 + r^2) * t^2 def F(r, t): return np.sin(r * t) / (1 + r * r) * t * t r0, t0 = 0.7, 1.3 R = Jet(I(r0), r=I(1.0)); T = Jet(I(t0), t=I(1.0)) one = Jet(I(1.0)) J = mul(mul(sin(mul(R, T)), inv(add(one, sqr(R)))), sqr(T)) h = 1e-4 fd_r = (F(r0 + h, t0) - F(r0 - h, t0)) / (2 * h); fd_t = (F(r0, t0 + h) - F(r0, t0 - h)) / (2 * h) fd_rr = (F(r0 + h, t0) - 2 * F(r0, t0) + F(r0 - h, t0)) / h ** 2 fd_tt = (F(r0, t0 + h) - 2 * F(r0, t0) + F(r0, t0 - h)) / h ** 2 fd_rt = (F(r0 + h, t0 + h) - F(r0 + h, t0 - h) - F(r0 - h, t0 + h) + F(r0 - h, t0 - h)) / (4 * h * h) for name, comp, ref in (('v', J.v, F(r0, t0)), ('r', J.r, fd_r), ('t', J.t, fd_t), ('rr', J.rr, fd_rr), ('rt', J.rt, fd_rt), ('tt', J.tt, fd_tt)): assert abs(float(comp.lo) - ref) < 1e-6 and abs(float(comp.hi) - ref) < 1e-6, (name, float(comp.lo), ref) # the same for the cosine: F2 = r^2 (1 - cos(r t^2)) def F2(r, t): return r * r * (1.0 - np.cos(r * t * t)) J = mul(sqr(R), sub(one, cos(mul(R, sqr(T))))) fd = dict(v=F2(r0, t0), r=(F2(r0 + h, t0) - F2(r0 - h, t0)) / (2 * h), t=(F2(r0, t0 + h) - F2(r0, t0 - h)) / (2 * h), rr=(F2(r0 + h, t0) - 2 * F2(r0, t0) + F2(r0 - h, t0)) / h ** 2, tt=(F2(r0, t0 + h) - 2 * F2(r0, t0) + F2(r0, t0 - h)) / h ** 2, rt=(F2(r0 + h, t0 + h) - F2(r0 + h, t0 - h) - F2(r0 - h, t0 + h) + F2(r0 - h, t0 - h)) / (4 * h * h)) for name in ('v', 'r', 't', 'rr', 'rt', 'tt'): comp = getattr(J, name) assert abs(float(comp.lo) - fd[name]) < 1e-6 and abs(float(comp.hi) - fd[name]) < 1e-6, (name, float(comp.lo), fd[name]) return wid if __name__ == "__main__": w = selftest() print(f"pi in [{PI_LO!r}, {PI_HI!r}]; max width of point enclosures of sin/cos on [-4.9, 4.9]: {w:.2e}; selftest ok")