Repository navigation
Expand file tree
/
Copy path_rational_interval.py
More file actions
334 lines (261 loc) · 11.5 KB
/
Copy path_rational_interval.py
File metadata and controls
334 lines (261 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
"""Small outward rational intervals for conditional continuous enclosures.
Every endpoint is rounded outwards to a fixed dyadic grid. Elementary bounds
use the existing rational Machin pi/cosine owners and alternating arctangent
series. Unit-interval exponential decay reuses the exact-time Taylor owner.
These are numerical enclosures, not assertions about any model or
trajectory. Wide or unresolved bounds must be handled by their caller.
"""
from __future__ import annotations
from dataclasses import dataclass
from fractions import Fraction as Q
from functools import lru_cache
from math import isqrt
from typing import TypeAlias, cast
from .._exact_time import exact_or_represented_real, exp_unit_bounds
from ._phase_midpoint import _pi_bounds
from ._phase_resultant_chamber import certified_cosine_bounds
__all__ = (
"I",
"RationalInterval",
"INTERVAL_BITS",
"INTERVAL_METHOD",
"EXP_NEG_UNIT_METHOD",
"pi_interval",
"sin",
"cos",
"atan",
"atan_ratio",
"arg",
"sqrt",
"exp_neg_unit",
)
INTERVAL_BITS = 128
INTERVAL_METHOD = "rational_outward_dyadic128_machin_trigonometry_v1"
EXP_NEG_UNIT_METHOD = "shared_rational_exp_unit_reciprocal_dyadic128_v1"
_SCALE = 1 << INTERVAL_BITS
_ATAN_TERMS = 64
def _exact(value: object) -> Q:
if isinstance(value, Q):
return exact_or_represented_real(value, "interval endpoint")
if type(value) is int:
return Q(value)
raise TypeError("interval endpoints require exact Fraction or integer values")
def _down(value: Q) -> Q:
return Q((value.numerator * _SCALE) // value.denominator, _SCALE)
def _up(value: Q) -> Q:
return Q(-((-value.numerator * _SCALE) // value.denominator), _SCALE)
@dataclass(frozen=True, slots=True, init=False)
class I: # noqa: E742 - conventional private interval-arithmetic notation
"""Immutable bounded interval with outward 128-bit dyadic endpoints.
Construction retains the supplied real interval by outward rounding;
even a single non-dyadic rational can therefore have positive width.
Fraction components use Python integers before rounding or arithmetic.
Floats and booleans require an explicit admission outside this kernel.
"""
lo: Q
hi: Q
def __init__(self, lo: int | Q, hi: int | Q | None = None) -> None:
lo = _exact(lo)
hi = lo if hi is None else _exact(hi)
if lo > hi:
raise ValueError("interval lower endpoint exceeds upper endpoint")
object.__setattr__(self, "lo", _down(lo))
object.__setattr__(self, "hi", _up(hi))
@classmethod
def point(cls, value: int | Q) -> I:
"""Enclose an exact rational point, retaining rounding uncertainty."""
return cls(value)
@classmethod
def coerce(cls, value: IntervalValue) -> I:
"""Admit an existing interval or an exact rational scalar."""
if isinstance(value, cls):
return value
# The constructor admits only scalars here and rejects a foreign interval subclass.
return cls(cast("int | Q", value))
@property
def midpoint(self) -> Q:
return (self.lo + self.hi) / 2
@property
def radius(self) -> Q:
return (self.hi - self.lo) / 2
@property
def width(self) -> Q:
return self.hi - self.lo
@property
def abs_max(self) -> Q:
return max(abs(self.lo), abs(self.hi))
def contains(self, value: object) -> bool:
"""Whether the whole supplied rational point/interval is enclosed."""
if isinstance(value, I):
return self.lo <= value.lo and value.hi <= self.hi
value = _exact(value)
return self.lo <= value <= self.hi
def __contains__(self, value: object) -> bool:
return self.contains(value)
def subset_of(self, other: IntervalValue) -> bool:
return I.coerce(other).contains(self)
def hull(self, other: IntervalValue) -> I:
other = I.coerce(other)
return I(min(self.lo, other.lo), max(self.hi, other.hi))
def __neg__(self) -> I:
return I(-self.hi, -self.lo)
def __pos__(self) -> I:
return self
def __abs__(self) -> I:
return I(
0 if self.contains(0) else min(abs(self.lo), abs(self.hi)), self.abs_max
)
def __add__(self, other: IntervalValue) -> I:
other = I.coerce(other)
return I(self.lo + other.lo, self.hi + other.hi)
__radd__ = __add__
def __sub__(self, other: IntervalValue) -> I:
other = I.coerce(other)
return I(self.lo - other.hi, self.hi - other.lo)
def __rsub__(self, other: IntervalValue) -> I:
return I.coerce(other) - self
def __mul__(self, other: IntervalValue) -> I:
other = I.coerce(other)
corners = (
self.lo * other.lo,
self.lo * other.hi,
self.hi * other.lo,
self.hi * other.hi,
)
return I(min(corners), max(corners))
__rmul__ = __mul__
def reciprocal(self) -> I:
if self.contains(0):
raise ZeroDivisionError("interval denominator contains zero")
return I(1 / self.hi, 1 / self.lo)
def __truediv__(self, other: IntervalValue) -> I:
return self * I.coerce(other).reciprocal()
def __rtruediv__(self, other: IntervalValue) -> I:
return I.coerce(other) / self
def __pow__(self, exponent: int) -> I:
if type(exponent) is not int:
raise TypeError("interval powers require an integer exponent")
if exponent < 0:
return (self ** (-exponent)).reciprocal()
if not exponent:
return I(1)
endpoints = (self.lo**exponent, self.hi**exponent)
lower = 0 if exponent % 2 == 0 and self.contains(0) else min(endpoints)
return I(lower, max(endpoints))
RationalInterval = I
IntervalValue: TypeAlias = I | int | Q
@lru_cache(maxsize=1)
def pi_interval() -> I:
"""Enclose mathematical pi using the shared Machin-series owner."""
return I(*_pi_bounds())
def exp_neg_unit(value: IntervalValue) -> I:
"""Enclose ``exp(-s)`` for the whole input interval within ``[0, 1]``.
Decreasing monotonicity reverses the endpoint order. Positive exponential
bounds come from the shared exact-time Taylor series and its rigorous
tail; their exact reciprocals are rounded outward only at the result.
Zero maps exactly to one. This narrow numerical domain is an explicit
work limit, not clipping or extrapolation of an unsupported input.
As elsewhere in this kernel, scalars must be exact integers or Fractions;
callers admit represented-real observations before constructing intervals.
``EXP_NEG_UNIT_METHOD`` identifies this bound without changing the existing
trigonometric ``INTERVAL_METHOD`` provenance.
"""
value = I.coerce(value)
if value.lo < 0 or value.hi > 1:
raise ValueError("exponential-decay interval must lie in [0, 1]")
lower_at_lo, upper_at_lo = exp_unit_bounds(value.lo)
if value.lo == value.hi:
upper_at_hi = upper_at_lo
else:
_, upper_at_hi = exp_unit_bounds(value.hi)
return I(1 / upper_at_hi, 1 / lower_at_lo)
def sqrt(value: IntervalValue) -> I:
"""Enclose the nonnegative square root by exact integer inequalities.
Every admitted endpoint must be nonnegative. An interval crossing zero
is rejected rather than silently clipped to an assumed physical domain.
Integer square roots locate the adjacent dyadic grid points without a
floating estimate, including very small and very large exact inputs.
"""
value = I.coerce(value)
if value.lo < 0:
raise ValueError("square-root interval must be nonnegative")
def floor_root(endpoint: Q) -> int:
scaled = endpoint.numerator * _SCALE * _SCALE
return isqrt(scaled // endpoint.denominator)
lower = floor_root(value.lo)
upper = floor_root(value.hi)
if Q(upper, _SCALE) ** 2 < value.hi:
upper += 1
return I(Q(lower, _SCALE), Q(upper, _SCALE))
def cos(value: IntervalValue) -> I:
"""Enclose cosine with midpoint bounds and its global unit Lipschitz bound."""
value = I.coerce(value)
lower, upper = certified_cosine_bounds(value.midpoint, terms=32, bits=128)
return I(max(Q(-1), lower - value.radius), min(Q(1), upper + value.radius))
def sin(value: IntervalValue) -> I:
"""Enclose sine through cos(pi/2-x), including mathematical pi uncertainty."""
return cos(pi_interval() / 2 - I.coerce(value))
def _small_atan_ratio(value: Q) -> I:
"""Enclose atan(t)/t for exact 0<=t<=1/2, continuously one at zero.
The first 64 terms end with a negative term. The omitted alternating
tail is positive and at most t**128/129. Interval arithmetic encloses
all rounding in the partial sum separately from this analytic tail.
"""
if value == 0:
return I(1)
square = I(value) ** 2
term = partial = I(1)
for index in range(1, _ATAN_TERMS):
term = -term * square
partial = partial + term / (2 * index + 1)
remainder = (square**_ATAN_TERMS).hi / (2 * _ATAN_TERMS + 1)
return partial + I(0, remainder)
@lru_cache(maxsize=4096)
def _atan_point(value: Q) -> I:
if value < 0:
return -_atan_point(-value)
if value <= Q(1, 2):
return I(value) * _small_atan_ratio(value)
if value <= 1:
# The transformed argument belongs to [-1/3, 0]. Keeping it exact
# avoids introducing a branch decision from a rounded denominator.
reduced = (value - 1) / (value + 1)
return pi_interval() / 4 + _atan_point(reduced)
return pi_interval() / 2 - _atan_point(1 / value)
def atan(value: IntervalValue) -> I:
"""Enclose the principal arctangent using monotonicity and rational series."""
value = I.coerce(value)
return I(_atan_point(value.lo).lo, _atan_point(value.hi).hi)
def arg(real: IntervalValue, imaginary: IntervalValue) -> I:
"""Enclose principal Arg(real+i*imaginary) on a whole regular rectangle.
The nonpositive real ray, including zero, is excluded. A rectangle must
have strictly positive real part or a sign-separated imaginary part;
intervals intersecting the cut reject, including unresolved rounded
boxes. The positive real axis is regular and has argument zero.
A right-half-plane chart uses atan(imaginary/real). On the upper/lower
chart, +/-pi/2-atan(real/imaginary) avoids division by a real interval
crossing zero. No floating branch convention or represented pi decides
admission. The returned enclosure may meet a branch endpoint through
conservative rounding; it does not claim that such an endpoint occurs.
"""
real, imaginary = I.coerce(real), I.coerce(imaginary)
if real.lo > 0:
return atan(imaginary / real)
if imaginary.lo > 0:
return pi_interval() / 2 - atan(real / imaginary)
if imaginary.hi < 0:
return -pi_interval() / 2 - atan(real / imaginary)
raise ValueError("principal argument rectangle intersects the nonpositive real ray")
@lru_cache(maxsize=4096)
def _atan_ratio_point(value: Q) -> I:
if value <= Q(1, 2):
return _small_atan_ratio(value)
return _atan_point(value) / I(value)
def atan_ratio(value: IntervalValue) -> I:
"""Enclose the continuous even function atan(t)/t, equal to one at zero.
The integral representation integral_0^1 1/(1+t*t*s*s) ds proves it is
decreasing in abs(t). This handles intervals crossing zero without a
division by an interval containing zero or a cancellation near zero.
"""
absolute = abs(I.coerce(value))
return I(_atan_ratio_point(absolute.hi).lo, _atan_ratio_point(absolute.lo).hi)