from decimal import Context, Decimal, ROUND_HALF_EVEN from functools import lru_cache from fractions import Fraction from itertools import product from math import inf, isfinite, nextafter import unittest _CONTEXT = Context(prec=34, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999) def _float_bound(value, upper): rounded = float(value) if not isfinite(rounded): raise OverflowError('Proof endpoint is outside the finite binary64 range') lift = Decimal.from_float if isinstance(value, Decimal) else Fraction.from_float if upper: if lift(rounded) < value: rounded = nextafter(rounded, inf) if lift(rounded) < value: raise ArithmeticError('Upper endpoint conversion failed') else: if lift(rounded) > value: rounded = nextafter(rounded, -inf) if lift(rounded) > value: raise ArithmeticError('Lower endpoint conversion failed') if not isfinite(rounded): raise OverflowError('Directed endpoint is outside the finite binary64 range') return rounded @lru_cache(maxsize=8192) def _transcendental(value, operation): if not isfinite(value): raise ValueError('Expected a finite binary64 endpoint') data = Decimal.from_float(value) if operation == 'ln': if value <= 0: raise ValueError('Expected a positive logarithm argument') if value == 1: return (0.0, 0.0) rounded = data.ln(context=_CONTEXT) else: if value == 0: return (1.0, 1.0) rounded = data.exp(context=_CONTEXT) return (_float_bound(rounded.next_minus(context=_CONTEXT), upper=False), _float_bound(rounded.next_plus(context=_CONTEXT), upper=True)) def log_bounds(value): return _transcendental(value, 'ln') def exp_bounds(value): return _transcendental(value, 'exp') def derivative_coefficient_bounds(coefficients): intervals = [] for index, value in enumerate(coefficients[1:], 1): exact = index * Fraction.from_float(value) intervals.append((_float_bound(exact, upper=False), _float_bound(exact, upper=True))) return tuple(intervals) def clipped_mirror(root_box, anchor, selected_in): values = (*root_box, anchor, *selected_in) if len(root_box) != 2 or len(selected_in) != 2 or not all(isfinite(x) for x in values): raise ValueError('Mirror clipping requires finite binary64 endpoints') start, end = map(Fraction.from_float, root_box) center = Fraction.from_float(anchor) hole_start, hole_end = map(Fraction.from_float, selected_in) if start > end or hole_start >= hole_end: raise ValueError('Invalid root box or open source hole') if end < center: lo, hi = max(end, hole_start), min(2 * center - end, hole_end) elif start > center: lo, hi = max(2 * center - start, hole_start), min(start, hole_end) else: return None if hi <= lo: return None inward = _float_bound(lo, upper=True), _float_bound(hi, upper=False) return inward if inward[0] < inward[1] else None def _log_series(value): ratio = (value - 1) / (value + 1) square = ratio * ratio total, term = Fraction(), ratio for index in range(48): total += 2 * term / (2 * index + 1) term *= square tail = 2 * abs(term) / (97 * (1 - square)) return total - tail, total + tail def _exp_series(value): if value < 0: lower, upper = _exp_series(-value) return 1 / upper, 1 / lower if value > 2: raise ValueError('Exact series test helper is restricted to |x| <= 2') total = term = Fraction(1) for index in range(1, 49): term *= value / index total += term return total, total + (term * value / 49) / (1 - value / 50) class BoundsTests(unittest.TestCase): def check_contains(self, actual, reference): self.assertLessEqual(Fraction.from_float(actual[0]), reference[0]) self.assertGreaterEqual(Fraction.from_float(actual[1]), reference[1]) def test_log_against_fraction_series(self): for value in (0.5, 0.6, 0.99, 1.01, 1.17, 1.9, 2.0): self.check_contains(log_bounds(value), _log_series(Fraction.from_float(value))) self.assertEqual(log_bounds(1.0), (0.0, 0.0)) with self.assertRaises(ValueError): log_bounds(0.0) def test_exp_against_fraction_series(self): for value in (-2.0, -1.1, -0.01, 0.01, 0.75, 1.1, 2.0): self.check_contains(exp_bounds(value), _exp_series(Fraction.from_float(value))) self.assertEqual(exp_bounds(0.0), (1.0, 1.0)) def test_derivative_factors(self): coefs = (0.0, 0.1, -0.1, 0.1, 0.1, -0.1, 0.1) exact = 3 * Fraction.from_float(coefs[3]) self.assertNotEqual(Fraction.from_float(3.0 * coefs[3]), exact) for index, interval in enumerate(derivative_coefficient_bounds(coefs), 1): exact = index * Fraction.from_float(coefs[index]) self.check_contains(interval, (exact, exact)) def test_clipped_mirror_with_ties_and_endpoints(self): grid = [index / 4 for index in range(25)] self.assertEqual(clipped_mirror((3.0, 3.0), 5.0, (1.0, 4.0)), (3.0, 4.0)) for (ha, hb), anchor in product(((0.0, 2.0), (1.0, 4.0), (2.0, 6.0)), grid): for first, second in product(grid, repeat=2): hits = [root for root in (first, second) if ha < root < hb] if not hits: continue root = min(hits, key=lambda value: abs(value - anchor)) hole = clipped_mirror((root, root), anchor, (ha, hb)) if hole: self.assertFalse(any(hole[0] < value < hole[1] for value in (first, second))) def test_mirror_is_clipped_to_each_source_hole(self): self.assertEqual(clipped_mirror((3.0, 3.0), 5.0, (1.0, 4.0)), (3.0, 4.0)) self.assertIsNone(clipped_mirror((3.0, 3.0), 5.0, (1.0, 3.0))) self.assertEqual(clipped_mirror((7.0, 7.0), 5.0, (6.0, 9.0)), (6.0, 7.0)) self.assertIsNone(clipped_mirror((2.0, 3.0), 2.5, (1.0, 4.0))) def test_nonfinite_mirror_inputs_are_rejected(self): with self.assertRaises(ValueError): clipped_mirror((1.0, float('inf')), 2.0, (0.0, 3.0)) if __name__ == '__main__': unittest.main(verbosity=2)