interval design
interval computes with sets of real numbers instead of single
approximations. This page states the mathematical contract, derives the
formulas the code uses, explains the choices behind them, and lists what the
package does not do. The API reference documents each
function; the tutorial shows them in use.
Design goal
A floating-point computation returns a number near the true result, with an
error that the caller has to estimate separately. interval returns an
interval that provably contains the true result, at any working precision, so
that the error bound is part of the value. Three requirements follow:
- Inclusion before tightness. Every operation returns a superset of the exact image of its operands. A wider result is acceptable; a result that misses a possible value is a bug.
- Explicit semantics. Precision, target format, flags and decorations are values passed in and returned, never process-global state (no hardware rounding-mode switching).
- Standard vocabulary. Sets, relations and decorations follow IEEE 1788-201511 IEEE Std 1788-2015, IEEE Standard for Interval Arithmetic. The package follows its set-based flavor. , so results can be checked against its test corpus (see conformance).
Mathematical background
Intervals and the inclusion property
An interval is a set with , and , or the empty set . Following the set-based model of IEEE 1788, infinite endpoints only say that the set is unbounded; the elements are always real. The whole line is called Entire.
For a real function with domain , the range over a box is
and its hull is the smallest interval containing it. An interval extension of is a map with for every box. Points outside are ignored rather than reported as errors: and . Whether a domain violation occurred is reported separately, by decorations.
Every public operation of Interval is an interval extension; no exception
is listed at present (see Known limitations). Composition then gives the result
that justifies the package:
Fundamental theorem of interval arithmetic.22 R. E. Moore, Interval Analysis, Prentice-Hall, 1966; and Moore, Kearfott, Cloud, Introduction to Interval Analysis, SIAM, 2009, Thm. 5.1. If an expression is evaluated with an interval extension for each operation, the result contains the value of the expression at every point of the input box where the expression is defined.
Proof. By induction on the expression. A variable evaluates to . For , let be a point where is defined; then each is defined at and, by the induction hypothesis, , the interval value of . Since is defined at and extends ,
The full argument, with the lemmas below, is in the attachment:
Outward rounding
Endpoints are Binary numbers with significant bits, so exact endpoint
values must be rounded. Write for the -bit binary numbers and
Three properties follow directly from these definitions:
(ii) holds because the set maximized for contains the one for ; (iii) follows from (ii), since the minimum over is attained at . Hence, if and for a set ,
This is the only way rounding enters the package: each operation computes a
lower bound and an upper bound of the exact range and stores
and . Property (iii) means
it does not matter whether candidates are rounded before or after taking the
minimum; the code rounds the extremal candidate once (quantize_interval).
The width added by rounding is at most one unit in the last place per endpoint. For the -bit numbers near are spaced apart, so , and likewise for . For a sum with exact range :
using . Widths
therefore grow additively through a computation, plus a relative
per rounding. The relative bound needs inside the normal range of
Binary, with
and . Below
the directed kernels round on a subnormal grid, and the error is only bounded
absolutely, by ; above the range an upper endpoint
becomes . Both happen only for magnitudes near .
Endpoint formulas
Interval stores the two endpoints (see
Endpoints, not midpoint and radius), so
each operation is a formula in the endpoints.
Sum and difference. is increasing in both arguments and is increasing in and decreasing in , so the extremes over the box are at the corners that make each argument extreme in the right direction:
Product. For fixed , is affine, so its extrema over lie at or ; applying the same argument to gives
The sign pattern decides which elements of can be extremal. If
the product is increasing in both
arguments, so the range is ; the other single-sign cases follow from
, which gives the table used by
multiplication_bounds:
| lower | upper | ||
|---|---|---|---|
| other (one of them has in its interior) |
The first four rows cover the cases where both operands have constant sign (an operand with a zero endpoint, such as , has constant sign; when two rows apply they give the same products). The last row covers the five remaining cases, in which at least one operand straddles 0. Say . The minimum of is , because and have opposite signs for any . If it were attained at , then , hence gives ; if at , then and . Either way the minimum is also attained at or (and a minimum of 0 at means , so as well). The maximum and the case where straddles 0 are symmetric. So two products suffice for the four single-sign rows and four for the rest.
For unbounded intervals all four products are formed with . This is the right limit for the set-based model: if and , the products with and fixed tend to 0, while the unbounded growth is already represented by the other corners ( when ).
Division. IEEE 1788 defines . When , is continuous and decreasing on , so and ; the code evaluates the selected endpoint quotients directly with directed division instead of rounding twice. When :
- : no admissible , the result is .
- , : approaches 0 from both sides, so is unbounded in both directions: Entire.
- with and , : as with , , and the smallest quotient is (0 when ), so the result is . The cases and are mirror images, obtained from . If straddles 0, both signs are unbounded: Entire.
- and : every admissible quotient is 0.
- An Empty operand gives Empty.
From midpoint–radius to endpoints
Users often know a value as . Interval::from_midpoint_radius(c, r, precision=p)
is the hull in the format of bits of the interval (IEEE
1788-2015 12.12.7, midRadToInterval): it stores
each end the exact sum rounded once in its direction (sub_ctx toward negative and
add_ctx toward positive of binary, whose operands are exact whatever their
precision). The interval contains because a directed rounding never
crosses the value, and it is the tightest interval of the format that does. When
and are numbers of the format nothing is rounded. Before 0.12 the center was
rounded to nearest, its rounding error was added to the radius on both sides and the
ends were kept exact with more than bits, which made the type
hold bounds that were not numbers of its format; the hull above replaced it (the
changelog states the largest difference). with_precision rounds the endpoints
outward directly, which encloses the input at every precision and is the tightest
representable enclosure, so it has no rounding-mode argument. The midpoint-radius view of the interval is the pair that IEEE 1788-2015 12.12.8 defines: to_midpoint_radius_string prints midpoint() and radius(), numbers of the format of bits. mid is the exact center rounded to nearest (ties to even), and rad is the smallest number of the format with the interval inside for that rounded : radius measures from midpoint, it is the larger of and , rounded up, so the printed pair encloses the interval (Interval::radius). The half-width around the exact center would be too small when the center is not representable (it was returned as radius before 0.12, issue 477); and the exact center of bounds that are billions of places apart is a number of billions of bits, which a text view cannot print: before 0.12 the text printed the exact center and half-width, with a stand-in beyond a gap of 65,536 places that was not the center.
The dependency problem
The fundamental theorem treats every occurrence of a variable as an independent point. For ,
The result is correct (it contains 0) but not tight: interval subtraction is
the extension of , and the box
contains and . In
general only holds. A second
theorem of Moore’s gives equality, in exact arithmetic and for continuous
operations, when each variable occurs at most once in the expression; the
condition is sufficient, not necessary (
is exact for ). The same effect explains for
( but ) and
subdistributivity, . For
this reason the package provides single-occurrence operations — sqr,
pown, fma, hypot, cancel_minus and the elementary functions — whose
results are hulls of the true range (up to rounding) rather than products of
independent factors. Interval values also do not form a group under addition:
cancel_minus is the operation that undoes an addition, since
in
general.
Elementary functions: monotonicity, critical points and poles
For a continuous function the range over an interval is an interval, and its endpoints are attained at the endpoints of or at critical points inside it. The package uses three patterns.
-
Monotone functions (
exp,exp2,exp10,expm1,ln,log2,log10,log1p,sqrt,sinh,tanh,asinh,acosh,atanh,asin,atan, and the decreasingacos): the range over is (swapped for decreasing ), so only the endpoints are evaluated, the lower one rounded down and the upper one rounded up. A domain boundary inside the interval is replaced by the limit there ( as ). -
Functions with known extrema.
coshhas its minimum 1 at 0.pownwith even exponent has minimum 0 at 0.sinattains at with and at ;cosattains at and at . Between two consecutive critical points both functions are monotone, so withThe code encloses by , where are computed from a certified enclosure of . This set can only be too large: a spurious critical point widens the result to , a missed one would break inclusion. When it has four or more elements every residue occurs.
sinpi,cospiandtanpiuse the exact critical points , computed from the dyadic endpoints without any approximation of . -
Poles. is continuous and increasing between consecutive poles . If contains an odd index the interval may contain a pole and the result is Entire; otherwise it is . For
tanpi, where the pole positions are exact, a pole at an endpoint gives a half-unbounded result instead. Negative powers and division handle the pole at 0 by the rules of the previous sections.
pow(x, y) on the domain (and , ) writes
with . The map
is bilinear, so by the corner argument used for products its extrema over the
box are at the
corners, and is increasing: the extrema of are among the four
corner values. When , and the corner values
become the limits (for ) and (for ). The
code also adds the value 1 when the box crosses or ; such
a box contains a point where , so already lies between
the extreme corner values and the extra candidate is redundant but harmless.
atan2 is handled the same way: the result is when the box
crosses the branch cut on the negative axis, and otherwise the extrema
over the box are at corners, as the next section shows.
One evaluation per bound
A bound of an interval result needs one directed evaluation, not the two (down and up) of which half used to be discarded, and often not even a second endpoint. Directed rounding is monotone: if then and . So the lower bound over candidate points equals where minimises itself, and likewise for the upper bound. The results are therefore bit-identical to the evaluation of every candidate in both directions; only the argument that is the minimiser has to be written down, once per case.
| Operation | Evaluations before | After |
|---|---|---|
| interval division | 4 div_ctx | 2 (one directed quotient per bound) |
sqrt | 4 sqrt_ctx | 2 |
| product, one factor straddling zero, the other sign-definite | 4 products | 2 |
| product with an unbounded factor | 8 products | 4 (the coefficient product of a finite pair is shared by both directions) |
pown, even exponent, negative or zero-containing interval | 4 or 3 pown_ctx | 2 |
try_atan2 | 8 to 16 try_atan2_ctx | 2 |
try_sinpi, try_cospi | 4 | 2 (also 2 with one extremum inside, 0 with an extremum of each kind) |
try_sin, try_cos | 8 exact-rational series per refinement round, plus per round | 2 correctly rounded binary evaluations, and one enclosure |
try_tan | 8 series per round, plus per round | 2 evaluations, and one enclosure |
Division and square root. The lower bound of is one quotient of two endpoints (chosen by the signs, see the corner argument above) rounded down, the upper bound one quotient rounded up. The square root needs rounded down and rounded up.
Products. If straddles zero and (), then is nondecreasing for each and is nondecreasing for and nonincreasing for , so the minimum is and the maximum (the other three sign cases are mirror images). Two factors that both straddle zero keep the four products.
atan2. Away from the origin and the branch cut,
and
. For the angle is
nonincreasing in , so the minimum has and the maximum
; at that the angle is nondecreasing in if
, nonincreasing if , and constant () at . For
(with ) the angle is nondecreasing in and the
same rule applies to . If straddles zero the branch-cut
case has been excluded, so and both bounds sit at
(the minimum at , the maximum at
). A zero endpoint of belongs to the side of
the other endpoint: is the limit from
and the limit from . Every
edge of the box is therefore monotone and the extrema over a box are at
corners, also when the origin is a corner or lies on an edge, since the
angles seen near the origin are those of the neighbouring corners. The axis
points that earlier versions added are between these two extremes. A box
whose extreme corner is the origin (a degenerate box) uses the general
corner hull.
sinpi, cospi, sin, cos. With the index range of the previous
section, an extremum of each kind inside gives without evaluation.
Without any extremum inside, lies in one arc between two
consecutive extrema and the function is monotone there: sine increases
through an index and decreases through (when
contains an index), and otherwise the arc is ,
increasing for and decreasing for . Cosine is
sine shifted by one index. The lower bound is then the endpoint value rounded
down at the lower end of the arc direction and the upper bound the other
endpoint rounded up; with one extremum inside, the opposite bound is the
better of the two endpoints.
sin, cos, tan (try_ forms). Each endpoint value is the correctly
rounded value of the binary kernel in the directed mode, which is the value
the exact-rational series produced (it rounded an enclosure that rounded
uniquely). The enclosure of is needed only for the index range (the
critical points and the poles); it is taken once from certified_pi_interval
with bits, where is the working precision of the
first refinement round ( the precision of the interval, the binade of
the larger endpoint). Its width, about , is smaller than that of
the rational enclosure of the old refinement loop (about ), so
is contained in the first-round range of the old code. The old code
decided a pole at its first round too, so try_tan returns the whole
line only where the old code did. What is identical by construction: every
endpoint value, and the result whenever the old code needed no refinement
round. What is not: when the old code refined (an endpoint within about
of a multiple of ) it used a narrower of a later round, and
the new can then hold a spurious index, only for
(an absolute bound that does not depend on
the number of bits of the endpoint). A spurious extremum does not change a
sine or cosine bound, since that close to an extremum the directed value
already rounds to ; a spurious pole makes the tangent the whole line,
which keeps the inclusion property. The tests compare old and new bit for bit
on the binary64 number closest to a multiple of
() and on the correctly rounded and
with their neighbours at 24, 53 and 113 bits, and no input differs.
The non-try sin, cos and tan are these
try_ forms with a fallback: they return (Entire for tan) for an
argument the kernel cannot certify, which the try_ forms report as an
error.
Certified evaluation of transcendental endpoints
is not a dyadic number, so an endpoint needs a directed
rounding of the exact value: is a valid lower
endpoint and a valid upper endpoint by property
(i). This package does not implement the series itself. Each endpoint is
evaluated by the certified try_*_ctx function of
binary in an unbounded context of the interval’s
precision, rounded toward for a lower bound and toward for
an upper bound; those functions refine a working precision until the two
directed roundings agree (a Ziv-style acceptance test33 A. Ziv, “Fast evaluation of elementary mathematical functions with
correctly rounded last bit”, ACM TOMS 17(3), 1991; J.-M. Muller et al.,
Handbook of Floating-Point Arithmetic, 2nd ed., Birkhäuser, 2018, §10. ) and report a
certification failure when the work budget runs out.
What this package adds is the interval analysis around the point kernels:
the domain restriction (an argument outside the domain is dropped, and the
result is Empty when nothing is left, which is decided by comparisons before
any kernel runs), the monotonicity and critical-point analysis of the
previous section (which endpoint gives which bound, where an extremum of
sin or a pole of tan lies), the handling of infinite endpoints, and the
fallback range. An enclosure of is needed only to locate critical points
and poles of the trigonometric functions, and for the fallbacks of the inverse
trigonometric functions; it comes from the cached binary-splitting constant of
binary (atan(+inf) is correctly rounded in each direction,
and the scaling by 2 is exact).
The IEEE 1788 decoration model
A bare interval result says where the values lie, not whether the function was defined. IEEE 1788 attaches a decoration to each result of evaluating on a box :
| Decoration | Property |
|---|---|
com | is non-empty and bounded, , is continuous at each point of , and the result is bounded |
dac | is non-empty, and is continuous |
def | is non-empty and |
trv | always true |
ill | the value is NaI, not an interval |
The decorations are totally ordered by strength, , because each property implies the
next (continuity of at each point of implies continuity
of the restriction, but not conversely: atan2 restricted to a box lying on
its branch cut from above is continuous, while atan2 is not). A decorated
operation applied to decorated inputs
returns
Why the minimum is sound. Suppose was produced by
on with property , and has on the box
of the . If , each is defined on
with values in (inclusion property), and
is defined on those values, so is defined on
. If , the same holds for continuity,
because a composition of continuous functions is continuous. Boundedness for
com is a property of the final result and is checked on it. By induction
the decoration of a whole expression is a true statement about the expression
on the input box. This is what interval existence proofs need: for example,
if is bounded and
with decoration at least dac, the function is continuous on the compact
non-empty interval and maps it into itself, so Brouwer’s
theorem gives a fixed point in . Boundedness matters:
maps Entire into itself, continuously, without a fixed
point. Without the
decoration, would wrongly suggest that
is defined on .
The package computes from the operands by the domain tests listed in the
API reference: division
by an interval containing 0, a logarithm reaching , sqrt below 0,
a pole of tanpi or of a negative-degree rootn in the argument and so on
give trv; atan2 across its branch cut gives def (defined but
discontinuous) and touching the cut from above gives dac. Set operations
(intersection, convex_hull, cancel_*) are not point functions and always
give trv. The result is made canonical: an empty result is always trv
(the properties above require a non-empty box), and com on
an unbounded result becomes dac (this is how overflow is reported). NaI,
the result of an invalid decorated construction, absorbs every operation, and
is distinct from , which is a valid set.
Integer functions
sign, ceil, floor, trunc, roundTiesToEven and roundTiesToAway
(IEEE 1788-2015 Table 9.1) are nondecreasing with integer values, so the bare
result is and no rounding happens. Their
decoration needs one observation: a function with values in (or
) restricted to an interval is continuous exactly when it is
constant on it, by the intermediate value theorem. So the strongest
decoration of 11.2 is def when .
When is constant, dac holds, and com holds when in addition
is bounded and contains no point where is discontinuous
on the real line. With that last test
is an endpoint comparison, because a constant box lies in a single step of the
function:
| Function | Points of discontinuity | contains one iff |
|---|---|---|
ceil | integers, | |
floor | integers, | |
trunc | nonzero integers | : ; : ; : never |
sign | ||
roundTiesToEven, roundTiesToAway | or |
This is why the ITF1788 corpus has ceil([1.1, 2.0]_com) = [2, 2]_dac (the
restriction is constant, but is a point of discontinuity) next to
floor([-1.2, -1.1]_com) = [-2, -2]_com. An unbounded box is never com, and
is def for ceil, floor, trunc and the roundings (the function is not
constant on it), dac for sign on a half line that excludes 0. The
corpus’s 55 decorated integer-function cases and the tests of the package
(each function with the jump as the lower endpoint, the upper endpoint, a point
box and in the interior) agree with this rule.
Reverse multiplication and two-output division
(IEEE 1788-2015 10.5.5) is computed by cases on whether and . Both intervals are nonempty (otherwise the set is empty).
| Set | ||
|---|---|---|
| yes | yes | : for every |
| any | no | the interval quotient (closed endpoints; the endpoint 0 of an unattained limit is open when ) |
| no | empty | |
| no | , | only contributes: one or two components below |
In the last row let be the end of nearest to zero. The divisor values give when and when ; the values give when and when . A divisor side exists only when , respectively . The quotient is 0 and is the unattained end of the component, so that component is open there. Each finite quotient is rounded outward, which keeps the closure a valid enclosure and tight in the type (the exact endpoint is attained, because or is in ).
mul_rev_to_pair closes the components. mul_rev(b, c, x) intersects each
component, with its open ends, with the closed interval and
takes the hull of what is nonempty (a lower end and upper end meet
when , or and both ends are closed). This is why the hull of
the set and the intersection of with its hull differ: for
, the set avoids ,
so the prior gives Empty. All 533 corpus cases of mulRev,
mulRevTen and mulRevToPair agree with the construction.
Reverse functions of even and monotone algebraic functions
sqr_rev, abs_rev, cosh_rev and pown_rev (IEEE 1788-2015 10.5.4) share
one scheme. The preimage of under is a union of at
most two intervals, found from the inverse of at the ends of
after cutting to the range of :
- for an even (, , , an even ) with inverse on the positive side, and : the two pieces and ;
- for an odd with , increasing: ;
- for a negative power, is decreasing on each side of the pole 0, so the roles of the two ends swap, is excluded, and the end of a piece at 0 is open: the unbounded end of gives , which is only a limit.
Each finite end is one directed rounding of the exact root of one exact
endpoint (sqrt, rootn, acosh of a point interval), so the closed pieces are
the tightest in the type. The hull with the prior meets each
piece, with its open ends, with and takes the hull of the
nonempty parts, the same routine as mul_rev. The trivial decoration (trv)
is attached by the decorated forms. All 360 corpus cases of these functions in
libieeep1788_tests_rev.itl and abs_rev.itl agree.
Reverse sine, cosine and tangent
sin_rev, cos_rev and tan_rev (IEEE 1788-2015 10.5.4) return the hull of the part
of a periodic union of intervals that lies in the prior . A piece end has
the form with an integer ,
and one of , , of an endpoint of (a pole of
has no ). The result takes the piece ends that matter, so the
comparison of a prior end with a piece end has to be exact; a wrong answer there moves
a result end by a whole period (for example sin_rev([0, 0], x = [RU(pi), 6])).
Which piece ends can be floats. If with a nonzero float, then is algebraic, and so is . For the Lindemann-Weierstrass theorem says is transcendental, so cannot be algebraic; the same holds for and . Every end is therefore irrational (a pole and the ends from are nonzero rational multiples of ) except , which needs and : and , and . Those ends are compared with the prior by an exact test, and every other end has a strict answer for every float . A pole therefore never equals a float, and the trigonometric reverse functions need no open flag.
Comparison and rounding. Each end is evaluated as an enclosure at a working precision
, starting at bits ( the binary exponent of the larger prior end),
from the certified enclosure of and the certified asin, acos, atan of the
exact point . A comparison with a prior end is decided as soon as the enclosure
excludes , else is doubled. The value written for a result end is the outward
rounding of an enclosure that contains no float of the result precision, which is exactly
or ; here too is doubled until that holds. The first
step is enough for almost every input, and not for all: a float can lie within a small
fraction of an ulp of a multiple of , which is why the loop is needed. The loop is
capped at 12 doublings (the same budget as the certified forward functions). At the cap an
undecided comparison counts as met in both conditions (a piece that might meet the prior is
never dropped) and the end written for such a piece is the prior’s own end, a valid bound of
both possibilities; a rounding is that of the last enclosure. The result is then an enclosure
of the hull, possibly wider. A white-box test sets the cap to 0 and to 1 and checks, on cases
of the reference test, that the result contains the hull and stays inside the prior. The pinned ITF1788 corpus never leaves the first
step: its 136 cases need at most.
Pieces and indices. A piece belongs to a family
with (in units of
, the period is 4 for and and 2 for ). The first piece that reaches the lower prior end has
its upper end in a window of a dozen consecutive values of around , which is
computed exactly in rational arithmetic from the lower and upper bound of the enclosure of
, widened by a stated margin: an end lies in since
, so a piece below the window cannot reach and the
predecessor of a piece above it already does. The same holds at with the lower ends.
Every piece of the window is tested for meeting the prior (hi >= x_l and lo <= x_h, both
exact), the lower end of the result is the minimum over the met pieces of or
, and the upper end the maximum of or
; no two transcendental ends are compared with each other, since
is monotone. The work is two searches of a few pieces each, whatever
the prior spans, and its cost follows the number of bits of the period index through the
working precision. The only limit is the one of the forward functions: an end of the prior at
or beyond is kept (valid, not tight). It is decided before any work
(the working precision comes only from the ends inside it, and a prior whose finite ends are
all beyond it is returned at once), so such an end never costs at its precision.
Tightness against the corpus. The tests compare the result with an enumeration of every
piece (trig_reverse_reference_wbtest.mbt), with no index arithmetic in common with the
implementation, over 4,200 random cases at precisions 24 and 53 that include priors with an end next
to a piece end. Six distinct corpus cases (twelve with the decorated copies) have an
expected value that is one or two ulps wider than the hull; they are listed on the
conformance page.
Reverse power with an interval exponent
pow_rev1(b, c, x) (IEEE 1788-2015 10.5.4) reduces to the set division of mul_rev in logarithm
coordinates (see the API page): the pieces of
come from the same case split as
(whether , that is , and whether ), with the
sign of an end of decided by comparing the end of with 1. The end of
a piece is open (it comes from ); the zero part is a piece of its own;
is open when it is the limit of a quotient by an unbounded and attained when
; every other finite end is attained.
Exactness of an end , , finite. Write and with and odd, and . Then with , and is rational iff is a perfect -th power in , that is and (for this needs , a comparison, and then one integer root; for it needs , a divisibility test; no power of is formed). The value is then . There are three classes of end and each has its own line in the procedure:
| Class | When | Comparison with a prior end | Rounding |
|---|---|---|---|
| dyadic | or | exact (it is ) | exact with_precision |
| rational, not dyadic | and , for example | exact cross-multiplication | integer division with directed rounding |
| irrational | otherwise | the loop below | the loop below |
A rational that is not dyadic is never a float, so its comparisons are strict without any refinement. An
irrational value is not rational, so it differs from every float, and the loop terminates: the
working precision starts at , with the exponent of (the result
needs the absolute error of below ), and doubles up to the cap of 12 as in sin_rev; at the
cap an undecided comparison counts as met in both conditions and the end written for that piece is
the prior’s own end. The sign of is exact, so iff : the enclosure is strict
at the float 1, and an exponent such as , where , is decided at
once (, ). The stored range is decided with a certified upper bound of , by a test that is sufficient and never wrong. Above: every finite float is below ( is the exponent of the leading bit), so if the enclosure of lies wholly at or above the enclosure of the value is [largest finite float at bits, ], built explicitly, and a lower end then rounds down to the largest finite float of the result precision; the top binade is finite and goes through . Below: the stored values at bits go down to the leading bit , so if the enclosure of lies wholly at or below the enclosure is , the smallest positive stored value at bits, and an upper end rounds up to the smallest positive stored value of the result precision. Between the limits is used, with gradual underflow (the enclosure is at most one quantum wide). Interval::exp of an interval with an end past the range returns the range of the function at some precisions (issue #569); the point exp of the lower end is a tight bound, so the two ends give the enclosure. If the enclosure of straddles the upper limit, returns an infinite upper end; the loops stop with it only if its lower end is checked to be at least (the largest finite float at bits), which says exactly that the upper end is and the lower end rounds down to the largest finite float of the result at every precision , hence at every further precision; otherwise the loops go on to their cap. If it straddles the lower limit the loops go on and terminate, since the quantum shrinks with while the value is fixed. An exact dyadic end in the subnormal range is kept exact, at a datum precision of at least bits within pow_value_budget, where is the exponent of the coefficient’s lowest bit (the stored values at bits are the multiples of ; the leading-bit formula is too small for a coefficient of more than one bit), and the datum built is checked to carry the value asked (an exact class never carries a rounded value) (for example is the stored value , and needs 6 bits; the result for a point set is for every prior that contains it, in about 0.2 s); an exact end above (for example ), a rational end in the subnormal range, and a dyadic end below the budget are decided by the loop, which clamps at the limits (a rational is never a float, so its separation terminates at the first precision).
Budgets, in bits and not in terms of 53: the exactness test runs only for and within
pow_int_budget = 65,536 bits (an exact 65,535-bit square takes about 80 ms, against about 20 ms for
the forward sqrt of the same operand) and an exact value is materialised only within
pow_value_budget = 262,144 bits (a value of millions of bits would be built only to be rounded to
bits). Above a budget the end goes to the loop with its documented fallback. The corpus needs none of
this: its 429 cases need the first working precision of the loop at most ( at
, measured), and the oracle reproduces all of them.
Tests. The definition tests cover the classes (including a 2000-bit perfect square and a with 500
fractional bits), the open ends at 0 and 1 against a prior that touches them from both sides, and exponents
and prior ends of magnitude . The reference test
(pow_reverse_reference_wbtest.mbt) does not use the pieces: it evaluates the condition for a float
with the forward Interval::pow at 200 bits, since is monotone and its range
over is the interval pow(x, b), and checks, at precisions 24, 53 and 113, that every float
certainly in the set is in the result, that a point a quarter of a float outside either end that comes from
a piece is not in the set, and that the float one step inside is not certainly outside while the next one
is certainly inside. A sample runs in every test run; the long run is an interval gate stage.
Reverse power with an interval base
pow_rev2(a, c, x) (IEEE 1788-2015 10.5.4) is the same set division with the roles exchanged
(see the API page): the unknown is the exponent, and the set is
with and
, plus when and
. The pieces come from the same case split as pow_rev1 (whether and
whether , the signs of the logarithms being comparisons with 1), and a piece
end is the quotient , with the infinities and the open 0 as in
pow_rev1 (here no value is mapped through , so there is no end at 1).
Exactness of an end for floats and . Write and with and odd and positive (the exponents and carry the sign of the logarithms). is rational iff and are multiplicatively dependent, and then:
| Case | End |
|---|---|
| exactly one of , is 1 | irrational () |
| both exceed 1 | the multiplicative Euclidean algorithm gives with , and ; iff , else irrational |
The algorithm divides the larger odd integer by a power of the smaller, with
(so that ; it divides whenever both are
powers of one base), and an inexact division proves independence; a high power of a small base ( against )
takes a few steps, not one per factor. The exponents of are recovered by running the steps
backwards, and the exact check , is made before the value is used. The value
is a float iff the reduced denominator is a power of two (class dyadic), and otherwise a rational that is
not a float (compared by exact cross-multiplication, rounded by integer division with directed
rounding, the sign taken into account). An odd part beyond pow_int_budget = 65,536 bits gives the class
Unknown, decided by the loop like an irrational end.
Working precision. The first working precision of the loop is , with the exponent of the quotient: has a relative error of about also for an argument next to 1 (the enclosure of keeps its full width in bits), so only the integer part of the quotient costs bits. A base one unit from 1 gives a quotient of about , and the tests check that its enclosure is tight (adjacent floats) at precision 53.
Budgets, in bits: one call of the exactness test at the budget ( against , 65,524 bits) takes
about 7 ms, against about 6 ms for the forward pow of the same operand at 200 bits, so the budget of
pow_rev1 is kept. The corpus needs none of it: the oracle finds no irrational piece end among its 375 statements (every end is exact, a float or a rational), so the loop and its fallback are covered by the tests below and not by the corpus.
Corpus. Two statements of the corpus expect a value that is valid but wider than the hull
(powRev2 [0.25, 0.5] [2, inf] expects Entire and powRev2 [0.25, 1] [2, inf] expects , where
with needs ); they are refinements, with the oracle
(tools/itl_pow2_reverse_oracle.py, which derives the set from the corner quotients and shares no code with
interval) giving 373 equal and 2 refined of 375 statements.
Tests. The definition tests cover the classes (including the Euclid steps, against , and a
beyond-budget odd part), exact and rounded rational ends with their sign, the examples of the corpus, the open
ends at 0 against a prior that touches them, a base one unit from 1 on both sides, and bases, results and
prior ends of magnitude . The reference test (pow_reverse2_reference_wbtest.mbt) evaluates the
condition for a float with the forward Interval::pow at 200 bits (the range of over
is the interval pow(a, beta)) and checks, at precisions 24, 53 and 113, that every float
certainly in the set is in the result, that a point a quarter of a float outside an end that comes from a
piece is not in the set, and that the float one step inside is not certainly outside while the next one is
certainly inside. A sample runs in every test run; the long run is an interval gate stage.
Reverse arctangent of two arguments
atan2_rev1(b, c, x) and atan2_rev2(a, c, x) (IEEE 1788-2015 10.5.4, equations (6) and (7), Table 10.1; see
the API page). With
the set is the projection of the sector
on the axis of the unknown (the ordinate for Rev1, the
abscissa for Rev2), cut by the strip of the given operand: a point of the ray at the angle has the
ordinate and the abscissa . Away from the axis directions this is the product
(Rev1) or (Rev2) of an operand point and the trigonometric value, so each
piece is an interval product, and the hull is taken over the pieces inside the prior as for pow_rev1. Write
and (likewise ).
| Operation | Piece | Angles | Needs | Set |
|---|---|---|---|---|
| Rev1 | right | |||
| Rev1 | upper-left | , a subset of ; is attained | ||
| Rev1 | lower-left | , a subset of ; the end at is open | ||
| Rev1 | up, down | or in | or | |
| Rev2 | upper half-plane | ( decreases from to ) | ||
| Rev2 | lower half-plane | ; the end at is open | ||
| Rev2 | right, left | or in | or |
The tangent (cotangent) interval of a piece has one end per end of : the tangent of an end of
inside the region, or the limit at a boundary of the region: at for
the tangent (at and for the cotangent), 0 at , 0 and for the tangent. Whether an end of
is below or above , , , or is decided exactly, in seven zones
(atan2_zone): is irrational, so a float is never equal to a multiple of it, and only is an exact
angle; the enclosure of is refined until the float is separated. The product of the operand part with
the trigonometric interval is monotone in each variable, so each extreme is the product of two ends, chosen by the
signs of the ends of the trigonometric interval (no numerical comparison between corners is needed), and an end
is attained only if both factors are: the limit 0 of (when ) and the infinities are
not attained, and are, and is not.
Branch cut and origin. The angle is attained and never, so puts into the Rev1 set when (an end of the upper-left piece, attained) and into the Rev2 set when , while a with lower end gives a lower-left piece whose end at (the limit of at ) is open. The origin is excluded: for there are only the up and down pieces, so is not reachable and is Empty; for there are only the angles and , so is not in the set.
Exactness of an end. The exact ends are and the infinities. Every other end is
(Rev1) or (Rev2) with a nonzero float
operand end and a nonzero float angle, which is irrational: of a nonzero algebraic number is transcendental
(Lindemann-Weierstrass) and a nonzero rational times a transcendental number is transcendental, so the end differs from
every float, comparisons with a prior end are strict, and the loop of pow_rev1 (the working precision doubles up
to the cap of 12; an undecided comparison counts as met and the prior’s own end is written) terminates. No integer
test and no budget are involved. The first working precision is : the forward tan of a point has a relative
error of about also next to , and (the argument reduction runs at the working precision),
and the loop needs the value to a relative . An angle one float from gives a cotangent of order
(the tests check the result is two adjacent floats that contain the 200-bit reference).
Evidence. The ITF1788 corpus has no atan2Rev case, so the evidence is ours.
tools/itl_atan2_reverse_oracle.py (pure Python, 260 digits, no interval code) derives the exact hull by
polar rectangles (an angle interval times an operand part of one sign, with corner limits) and validates every
expected hull by the forward definition of the operation, which shares nothing with the case analysis. For a fixed
ordinate , is monotone and continuous in on each side of 0
(decreasing for , increasing for ; for it is 0 for and for ), so
its image over is an interval decided from the ends of , and is a member iff
the image meets (Rev2 likewise, with the ordinate part split at 0). The validation tests an
attained end, three points a geometric step inside each piece end (, , relative) and six
points beyond each end of the hull, inside the prior (, , , , 1 and 100 relative). The
generated file testdata/interval/generated/atan2_rev.itl (see its README) has 16,260 cases, run as the
atan2-reverse phase, counted apart from the ITF1788 total. The reference test
(atan2_reverse_reference_wbtest.mbt) evaluates membership of a float with the forward Interval::atan2 of points at
200 bits (the same monotone image, with the cut treated explicitly) and checks, at precisions 24, 53 and 113, that
every float certainly in the set is in the result, that a point a quarter of a float outside an end that comes from a
piece is not in the set, and that the float one step inside is not certainly outside while the next one is certainly
inside. The maximum working precision on the generated corpus is 149 bits (the first working precision, at ; none of the 6,813 evaluations of the loop doubled it).
Interval literals and text input
from_string (IEEE 1788-2015 textToInterval, 9.7, 12.11, 12.12.7, 13.2; see the
API page) is a hand-written parser of the portable
grammar (Tables 9.5 and 12.2) over the characters of the string. A number literal is read into one of four exact
descriptions: an infinity, a decimal (the digits without the point and the exponent minus the number of
digits after the point), a hexadecimal (the exponent minus four times the number of hexadecimal digits
after the point), or a rational with positive. An exponent field is saturated at in magnitude (beyond
every range). The uncertain form is turned into two decimal descriptions by the definition of 9.7.3: with
the number of digits after the point of , the bounds are with the integer of the digits
(one ulp being ; for the empty radius, half an ulp, as ), the direction or keeps
one side, and the radius is unbounded; the arithmetic is on big integers, so no rounding precedes the final one.
Rounding. Each bound is rounded once, outward and exactly: a decimal and a hexadecimal description go through
the correctly rounded directed conversions of Binary (from_string_ctx, from_hex_ctx, which accept any exponent),
and a rational is divided by integer division to a quotient of at least bits with the sticky remainder (the same
rule as the exact rational ends of pow_rev1). A literal whose exact value is beyond the stored range is therefore decided
by those conversions from the exponent without forming the value, and 1e400000000 has the lower end the largest finite
float and the upper end . Both converters accept an exponent field of any length (from_hex_ctx saturates it at like from_string_ctx; before issue 597 it rejected an exponent beyond and the parser clamped it). The invariants are checked: a failure of a converter or of the digit parser aborts instead of returning a bound.
The order . It is decided from the exact values, so rounding never makes a nonempty literal Empty and an empty one nonempty: two decimal bounds are compared by the adjusted exponent and then the digit strings (trailing zeros removed, the shorter padded with zeros), which needs no power of ten whatever the exponent; any other pair is first separated by roundings at 64 bits and otherwise compared by cross-multiplication of the exact numerators and denominators, a power being formed only for an exponent of magnitude at most 65,536. A pair that is neither separated nor within that limit (two bounds of different radices that agree to 64 bits and have an exponent beyond 65,536) is undecided: 12.12.7 case (b) allows it and requires the result to contain both bounds, so the result is the hull of the four roundings (a false positive, which the standard permits; a false negative is not possible).
Rejections. Every failed call is an Err of the parse kind whose message names the rule of the grammar or of
12.11 that was broken (a missing digit, the exponent field of a hexadecimal literal, the denominator of a rational, the order of the bounds,
an infinite bound on the wrong side, the characters after the literal, the decoration literal, a decoration not permitted
for the value by 11.4, a decoration on a bare literal). The test table asserts the reason of every rejected string. A literal
longer than interval_literal_max_length is not parsed and gives Entire (12.11.5).
Evidence. The independent oracle tools/interval_literal_oracle.py (pure Python, no interval code) evaluates a literal from whole-string
patterns (a special form, the two bound strings of an inf-sup form cut at the comma, the groups of an uncertain pattern) to an exact Fraction, derives the uncertain form from the definition of the
ulp, and rounds each bound with integer arithmetic against the stored range (gradual underflow to the quantum , the largest finite float
); it also checks every one of 20,000 rational literals against the rounded ends by cross-multiplication (the rounded lower end is not above the value
and the float below it is below, and likewise for the upper end). The generated table (9,919 literals: the vectors of Tables 9.4 and 12.1, the negative
examples, and random decimal, hexadecimal, rational, uncertain, decorated and special literals at precisions 24, 53 and 113, bare and decorated) is
compared with the parser in interval_literal_wbtest.mbt.
Relations: certainly and possibly
An interval stands for an unknown point, so a comparison of two intervals asks a quantified question. Two quantifiers give the useful relations:
For the first line, "" is . For "": if and are
finite they are elements, so ; if
or , a large or a
small violates , and the endpoint test is false as well. The second line is the
nonempty intersection of two intervals. “Possibly less” is the negation of
“certainly not less”, so the two families are dual: DefinitelyLt::definitely_lt(x, y) is
false exactly when some pair satisfies . With empty operands the
universal statements would be vacuously true, which would let a caller prove
anything from an empty enclosure; the DefinitelyLt and DefinitelyLe relations (and Overlaps, MaybeEq) therefore
return false for empty operands, whereas the IEEE 1788 relation precedes
() is defined to be vacuously true.
The set relations (subset, interior, disjoint, ==) and the
IEEE 1788 orders (less: and
, which reduces to comparing both
endpoint pairs) are evaluated by endpoint comparisons in the same way. None of
these relations is a total order, and the trait method
@lf_arith.Contains::contains(x, y) is set inclusion
, matching the enclosure reading of
the arithmetic traits.
Design decisions
Endpoints, not midpoint and radius
Problem. An interval can be stored as endpoints (inf–sup) or as a midpoint and radius , as in Arb.44 J. van der Hoeven, “Ball arithmetic”, 2009; F. Johansson, “Arb: efficient arbitrary-precision midpoint-radius interval arithmetic”, IEEE Trans. Computers 66(8), 2017.
Midpoint–radius arithmetic. With , and likewise for :
With a rounded midpoint , the rounding error is added, so
These are cheap (the radius needs only a few bits), but the product radius overestimates: for it gives while the exact product is . Rump showed that the width can grow by a factor up to per multiplication compared to inf–sup.55 S. M. Rump, “Fast and parallel interval arithmetic”, BIT 39(3), 1999.
Options. (a) midpoint–radius storage with low-precision radii; (b) endpoint storage with full-precision endpoints; (c) both.
Chosen: (b). IEEE 1788 is defined on endpoints, half-unbounded and empty
sets have no midpoint–radius form, and the hulls in the
endpoint formulas are exact before rounding, so
inf–sup results are as tight as the precision allows. The cost is that both
endpoints carry bits, so wide intervals at high precision store many
useless bits. The midpoint–radius view (from_midpoint_radius, midpoint, radius) is kept for users
who reason in , with the conversions derived
above.
Endpoint operations: one directed rounding of the exact result
Problem. Endpoint candidates can be computed with directed rounding at each step, or exactly and rounded once. Rounding at each step would not give the tightest enclosure; forming the exact value of a sum or a product by hand costs alignment and bookkeeping the binary layer already does.
Chosen. Every endpoint sum, difference and product of two Binary
endpoints is one directed contextual operation of binary (add_ctx,
sub_ctx, mul_ctx, fma_ctx) in a context of the precision of the
result and the direction of the endpoint: lower endpoints toward ,
upper endpoints toward , radii and widths upward. Each of them
computes as if its exact operands were summed or multiplied exactly and rounds
that value once, so by property (iii) the result is the tightest -bit
endpoint. The exponent range is the one of the library, so the three issues
that an exact route had to handle itself belong to the binary layer:
- Far addends. Adding and exactly aligns two
coefficients over two billion bits (about 750 MB for one interval addition,
issue #24).
add_ctxdoes not align them: a term whose leading bit lies beyond the rounding position only decides the side of the rounding, and it is a sticky bit there. Soundness and tightness do not depend on a bound for the distance, as the replacement of the small addend by a surrogate that earlier versions made here did, and no precision label of an operand enters. - The edge of the exponent range. A result beyond the range is clamped by the rounding mode of the operation: a lower endpoint to or the largest finite number, an upper endpoint to or the largest finite number, a tiny result to zero or the smallest positive number. This keeps, for example, an enclosure instead of collapsing it.
- Gradual underflow. A result below the normal range lies on the grid of the format, and the directed rounding goes to that grid, not to the grid of the few bits the exact result happens to have.
The sign of a zero that is the result of an exact cancellation is the one of the direction ( toward ); it is not part of the interval (see the observers). Division and square root, whose exact results are not dyadic, are computed directly with directed rounding at precision . The midpoint needs the exact half-sum of the two bounds, not a rounded one: it adds the bounds rounded toward zero to bits and makes the result odd when that rounding was inexact (round to odd), so that the one rounding that follows, to at most bits in any direction, is the rounding of the exact value; an exponent gap of less than 65,536 places gives the exact center.
Contexts and double rounding
IntervalContext carries a target precision and exponent range;
apply_ctx rounds endpoints outward into it and the *_ctx operations
compute at the operands’ precision and then apply the context. Rounding
twice is harmless for directed rounding when :
because (a -bit significand is a -bit one padded with
zeros): every below is in , hence below
, and conversely. So (x + y).apply_ctx(ctx) equals a
single outward rounding of the exact sum into the context whenever the
operands are at least as precise as the context. Overflow is resolved in the
enclosing direction: an upper endpoint above the range becomes , a
positive lower endpoint becomes the largest finite number (still below the
true value). Underflow rounds outward on the subnormal grid, so a tiny
positive upper bound becomes the smallest subnormal and never 0. The flags
are returned, never stored glointervaly.
Total and try_ forms
Problem. Certified evaluation can fail: the refinement budget may run out, or an argument may be too large to reduce. Aborting would break long computations; returning a silent wide interval hides a lost guarantee of tightness.
Chosen. Both, with one kernel. The try_ forms return an
ArithmeticError with a certification detail (operation, stage, reason,
precision). The total form is the try_ form with a fallback: when the try_
form fails it returns the range of the function over its domain, which keeps
the inclusion property: for exp, exp2, exp10, pow and
hypot, for expm1, Entire for the logarithms, sinh,
asinh, atanh, tan, tanpi and log1p, for sin, cos,
sinpi, cospi and tanh, for cosh, for
acosh, for atan and asin, for acos,
for atan2. The of a fallback is evaluated at no more
than 64 bits and rounded outward, so a fallback cannot fail at any precision.
The domain is decided before the kernel runs, so a failure is always a
certification failure and never a domain error: an argument outside the domain
gives Empty, a wide interval means the kernel gave up. Trigonometric reduction
is capped: when the larger endpoint magnitude is at least
, reduction would need more than that many bits, so the
try_ forms report a resource limit and the total forms return the fallback.
Why one kernel. Until this was settled the total forms of fifteen functions
had a kernel of their own (exact-rational series), which aborted at a high
precision (about 32,000 bits for ln, issue 449) and lost all relative
accuracy for a tiny argument in the hyperbolic functions, while the try_
forms used the binary kernels and had neither limit. Keeping two kernels
for the same function meant two sets of bugs, and results that depended on
which form the caller chose.
Decorations in a separate type
Problem. Decorations cost a field and a minimum per operation, and most users do not need them.
Chosen. Interval is the bare set; DecoratedInterval wraps it with a
decoration and the NaI state. Bare operations stay cheap and simple, and the
decorated type cannot be mixed with bare values by accident.
Precision as a tag
Each interval carries a precision tag; binary operations use the larger tag.
This keeps a sequence of operations at the precision of its most precise
input without a context argument, which is what a set-valued type needs to
compose with operators (x + y). An IntervalContext is used when a specific
format must be imposed.
Correctness and invariants
Representation invariant. A non-empty Interval has non-NaN endpoints,
, ,
and precision ; every construction path
ends in store_interval, which checks this and aborts otherwise. Empty is a
flag with endpoints .
Inclusion. Each public operation of Interval satisfies
, by the endpoint formulas and
Corollary 2 for arithmetic, by the critical-point analysis and certified
endpoint enclosures for elementary functions, and by the fallbacks for
uncertified cases. By the
fundamental theorem, so does every composition.
Tightness. Basic arithmetic, sqr, pown, fma, abs, min,
max, intersection, convex_hull of non-empty operands and
sqrt return the outward rounding of the exact hull, so each
endpoint is within one ulp of optimal. Trigonometric and arctangent endpoints
are correctly directed roundings when certified; the other elementary
functions are usually within a few ulps. Not tight: fallbacks; pown with
and 0 inside (Entire); with_precision and
normalized round the endpoints outward, which is the tightest enclosure and
the identity on an interval already representable at the target precision, so
convex_hull with an Empty operand and the checked capabilities do not widen
either.
Decorations. The decoration of a result is a true statement about the function evaluated, by the induction argument above.
Complexity. Arithmetic performs at most four endpoint products or two
sums, for -bit endpoints with multiplication cost , plus
alignment of at most about bits for sums. Elementary functions cost one
or two directed evaluations of the binary kernels at precision (see
binary for their cost), plus the index range for the
trigonometric functions.
Evidence. Package tests check directed endpoints, the far-addend and exponent-range cases, decorations and relations; the pinned ITF1788 corpus runs 6,632 cases in strict mode (see conformance).
Known limitations
No limitation is open at present. Decorated rootn with a negative degree
lowers the decoration to trv when 0 is in the argument, as the decoration
rules of IEEE 1788-2015 11.6 require; library/src/interval/interval_decorated_wbtest.mbt
checks degrees -1, -2 and -3.
Alternatives rejected
- Midpoint–radius storage (Arb-style): cheaper radii, but overestimating products and no representation for half-unbounded sets; see above.
- Hardware
Doubleendpoints with switched rounding modes: fixed precision, process-global state, and rounding-mode control is not available on every MoonBit target. - Round to nearest and inflate by one ulp (“epsilon inflation”): simpler, but about one ulp wider per endpoint than directed rounding, and only valid for operations whose nearest-rounded result is known to be within one ulp, which excludes most elementary function kernels.
- Aborting on uncertified elementary functions: a single hard argument
would stop a whole computation; the
try_forms cover callers who need the failure. - Treating division by zero-containing intervals as an error: IEEE 1788 defines these results as sets (Entire, half-unbounded or empty), and extended division is what makes interval Newton methods work.
Boundaries
The package deliberately does not:
- provide reverse versions of division and reciprocal (Table 10.1 does not require them: change
z = x / ytox = y zand usemul_rev); - promise tight results: fallbacks and the dependency problem may widen enclosures arbitrarily;
- define a total order on intervals, or treat
Eqas set equality; - convert decimal data outward on its own:
from_doubleandexactenclose binary values, and enclosing a decimal literal is the caller’s job (see the tutorial); - implement intervals over decimal endpoints, complex intervals, interval vectors or matrices, or Taylor models;
- report status through global flags: flags come back from
*_ctxcalls and decorations travel with values.
Footnotes
-
IEEE Std 1788-2015, IEEE Standard for Interval Arithmetic. The package follows its set-based flavor. ↩
-
R. E. Moore, Interval Analysis, Prentice-Hall, 1966; and Moore, Kearfott, Cloud, Introduction to Interval Analysis, SIAM, 2009, Thm. 5.1. ↩
-
A. Ziv, “Fast evaluation of elementary mathematical functions with correctly rounded last bit”, ACM TOMS 17(3), 1991; J.-M. Muller et al., Handbook of Floating-Point Arithmetic, 2nd ed., Birkhäuser, 2018, §10. ↩
-
J. van der Hoeven, “Ball arithmetic”, 2009; F. Johansson, “Arb: efficient arbitrary-precision midpoint-radius interval arithmetic”, IEEE Trans. Computers 66(8), 2017. ↩
-
S. M. Rump, “Fast and parallel interval arithmetic”, BIT 39(3), 1999. ↩