internal design

Design goal

The binary, decimal and interval cores all reduce their hard steps to exact integer arithmetic: aligning exponents, removing trailing zeros, dividing with a rounding mode, enclosing a ratio between two dyadics. internal states these steps as small BigInt functions with proved invariants, so that the tests of this package can check each one against an oracle and the cores can share what they have in common. It is internal so the cores can change the helpers together without a public compatibility promise.

On the current branch the sharing is partial. The decimal cores use the string splitter, round_positive_div, the power caches and digits10; every core uses the refinement budget and certified_failure. The hot paths of binary and the two decimal packages round with their own limb kernels (BinCoeff, and DecCoeff in the subpackage internal/decimal_kernel, which decimal and decimal_gda share), which implement the same rounding table as round_positive_div but are not built on it, and several helpers (round_shift, remove_factor10, trim_trailing_decimal_zeros, the CertifiedDyadic family) are exercised only by tests. The table on the API page lists the users of each helper.

Mathematical background

Integer division with remainder

For n≥0n \ge 0 and d>0d > 0 there are unique integers q,rq, r with n=qd+rn = qd + r and 0≤r<d0 \le r < d (Euclidean division). Then q=⌊n/d⌋q = \lfloor n/d \rfloor, and n/dn/d is an integer exactly when r=0r = 0. The fractional part is r/d∈[0,1)r/d \in [0, 1), and

rd⋚12  ⟺  2r⋚d.\frac{r}{d} \lesseqgtr \frac12 \iff 2r \lesseqgtr d .

Rounding to an integer

For a real xx and a rounding direction, ∘(x)\circ(x) is the integer chosen among ⌊x⌋\lfloor x \rfloor and ⌈x⌉\lceil x \rceil: toward zero, toward +∞+\infty, toward −∞-\infty, away from zero, or to the nearest with ties to the even candidate.11 IEEE 754-2019, clause 4.3, defines the rounding-direction attributes; the integer case is the same definition with Z\mathbb{Z} as the set of representable numbers.

Dyadic enclosures

A dyadic number is n⋅2−sn \cdot 2^{-s} with n∈Zn \in \mathbb{Z}, s≥0s \ge 0. For a real xx and a scale ss, the dyadics of scale ss around xx are ⌊x2s⌋2−s≤x≤⌈x2s⌉2−s\lfloor x 2^{s} \rfloor 2^{-s} \le x \le \lceil x 2^{s} \rceil 2^{-s}, an interval of width at most 2−s2^{-s}.

Design decisions

Magnitude and sign passed separately

round_positive_div(n, d, negative, mode) takes n≥0n \ge 0 and the sign of the true quotient as a flag. Sign-magnitude is how the cores store their coefficients, and directed rounding of a magnitude depends on the sign: rounding −2.5-2.5 toward −∞-\infty increases the magnitude. Keeping the sign as a separate argument makes the rule a single table and avoids negative remainders, whose convention differs between languages.

Powers of ten and five from a shared cache

Decimal scaling uses 10k10^{k} and the binary-decimal conversions use 5k5^{k} (because 10k=5k2k10^{k} = 5^{k} 2^{k} and the factor 2k2^{k} is a shift). The caches start with the 19 powers k≤18k \le 18 (101810^{18} is the largest power of ten below 2632^{63}) and are extended on demand up to k=4096k = 4096; larger powers are computed directly on each call, so that an extreme exponent cannot make the cache grow without bound.

Digit count without strings

digits10 starts from the estimate d0=⌊blog⁡102⌋+1d_0 = \lfloor b \log_{10} 2 \rfloor + 1, where bb is the bit length of ∣x∣|x|, and corrects it by comparison with powers of ten. Since 2b−1≤∣x∣<2b2^{b-1} \le |x| < 2^{b}, the true digit count dd satisfies

⌊(b−1)log⁡102⌋+1  ≤  d  ≤  ⌊blog⁡102⌋+1=d0,\lfloor (b-1) \log_{10} 2 \rfloor + 1 \;\le\; d \;\le\; \lfloor b \log_{10} 2 \rfloor + 1 = d_0 ,

and because log⁡102<1\log_{10} 2 < 1 the two bounds differ by at most one. So at most one downward correction is ever needed (the upward loop guards against floating-point error in the estimate), and the cost is a constant number of BigInt comparisons plus one power of ten.

Wide exponent parsing

A decimal context may set emax⁡e_{\max} anywhere in Int, and the context-free parse applies no exponent range at all, so no cap inside Int is safe: a literal exponent that is clamped to a smaller value can still be in range and silently changes the number. split_decimal_string_wide therefore returns the exponent qq as an Int64. The written exponent is read exactly up to 101810^{18} and saturates there; with at most 2312^{31} fraction digits, ∣q∣<1018+231|q| < 10^{18} + 2^{31}, so the subtraction never overflows Int64. A saturated qq lies far outside Int and so outside every exponent a value or context can hold, which means a caller that compares qq (plus the digit count) with Int and its context sees the same overflow or underflow as for the exact exponent. split_decimal_string keeps its Int signature and returns None when qq does not fit Int, rather than a different exponent.

Ziv-style refinement budget

The certified elementary functions evaluate an enclosure at a working precision pkp_k and accept the result when both ends round to the same target number (Ziv’s strategy22 A. Ziv, “Fast evaluation of elementary mathematical functions with correctly rounded last bit”, ACM TOMS 17(3), 1991. ); otherwise they retry at a higher precision. The budget fixes the schedule

pk+1=pk+max⁡(32,⌊pk/2⌋),k<L,p_{k+1} = p_k + \max\bigl(32, \lfloor p_k / 2 \rfloor\bigr), \qquad k < L ,

with L=12L = 12 refinements by default. For pk≥64p_k \ge 64 this is pk+⌊pk/2⌋=⌊3pk/2⌋p_k + \lfloor p_k/2 \rfloor = \lfloor 3 p_k / 2 \rfloor, geometric growth with ratio 3/23/2 up to the floor, so pL≈p0(3/2)Lp_L \approx p_0 (3/2)^{L} (about 130 p0130\,p_0 for L=12L = 12 and p0≥64p_0 \ge 64). For pk<64p_k < 64 the step is 3232 and pk+1/pk=1+32/pk>3/2p_{k+1}/p_k = 1 + 32/p_k > 3/2, so the ratio is at least 3/23/2 (up to the floor) at every step. If one attempt at precision pp costs C(p)≥c pC(p) \ge c\,p (at least linear), the total cost of all attempts is dominated by the last one:

∑k=0mC(pk)≤C(pm)∑j≥0(2/3)j=3 C(pm)when C(pk)≤(2/3)m−kC(pm),\sum_{k=0}^{m} C(p_k) \le C(p_m) \sum_{j \ge 0} (2/3)^{j} = 3\, C(p_m) \quad \text{when } C(p_k) \le (2/3)^{m-k} C(p_m),

which holds, up to the floors in the schedule, for C(p)=c pαC(p) = c\,p^{\alpha} with α≥1\alpha \ge 1 in the geometric phase. Exhaustion is reported with certified_failure, which records the target and final working precision, instead of returning a value that is not certified.

Correctness and invariants

Rounding table. Let n=qd+rn = qd + r with 0≤r<d0 \le r < d and x=(−1)σn/dx = (-1)^{\sigma} n/d. Then ∣∘(x)∣∈{q,q+1}|\circ(x)| \in \{q, q+1\}, with q+1q + 1 only if r>0r > 0, and round_positive_div returns ∣∘(x)∣|\circ(x)|:

toward zero:∣∘(x)∣=q,toward +∞:∣∘(x)∣=q+[r>0∧σ=0],toward −∞:∣∘(x)∣=q+[r>0∧σ=1],away from zero:∣∘(x)∣=q+[r>0],nearest even:∣∘(x)∣=q+[2r>d∨(2r=d∧q odd)].\begin{aligned} \text{toward zero:} &\quad |\circ(x)| = q, \\ \text{toward } +\infty: &\quad |\circ(x)| = q + [r > 0 \wedge \sigma = 0], \\ \text{toward } -\infty: &\quad |\circ(x)| = q + [r > 0 \wedge \sigma = 1], \\ \text{away from zero:} &\quad |\circ(x)| = q + [r > 0], \\ \text{nearest even:} &\quad |\circ(x)| = q + [2r > d \vee (2r = d \wedge q \text{ odd})] . \end{aligned}

Proof. ∣x∣=q+r/d|x| = q + r/d lies in [q,q+1)[q, q+1). Toward zero takes the smaller magnitude. Toward +∞+\infty takes the larger magnitude for a positive non-integer and the smaller for a negative one; toward −∞-\infty is the mirror image. Away from zero takes the larger magnitude for any non-integer. For nearest, the distance to qq is r/dr/d and to q+1q+1 is 1−r/d1 - r/d, so q+1q + 1 is nearer iff 2r>d2r > d, and 2r=d2r = d is the tie, broken toward the even one of q,q+1q, q+1, which is q+1q + 1 iff qq is odd. □\square

round_shift(m, s, …) is the case d=2sd = 2^{s} with q=m≫sq = m \gg s and r=m−(q≪s)r = m - (q \ll s), so the same table applies for m≥0m \ge 0. For m<0m < 0 the arithmetic shift gives q=⌊m/2s⌋<0q = \lfloor m/2^{s} \rfloor < 0 and 0≤r<2s0 \le r < 2^{s}, and the “magnitude” table is then applied to a negative qq; the result is not ±∣∘(x)∣\pm|\circ(x)| (for example m=−5m = -5, s=1s = 1, TowardZero gives −3-3). The function does not check the sign, so callers must pass magnitudes. The tests of this package check both functions against these formulas on ties and directed cases.

Factor removal. remove_factor10 and trim_trailing_decimal_zeros preserve c⋅10ec \cdot 10^{e}, removing one factor of 10 per step; the latter stops after max_drop steps.

Enclosure. certified_dyadic_fraction(n, d, s) returns ℓ=⌊n2s/d⌋2−s\ell = \lfloor n 2^{s} / d \rfloor 2^{-s} and u=⌈n2s/d⌉2−su = \lceil n 2^{s} / d \rceil 2^{-s}; from ⌊y⌋≤y≤⌈y⌉\lfloor y \rfloor \le y \le \lceil y \rceil with y=n2s/dy = n 2^{s}/d we get ℓ≤n/d≤u\ell \le n/d \le u and u−ℓ≤2−su - \ell \le 2^{-s}, with equality ℓ=u\ell = u iff y∈Zy \in \mathbb{Z}. The floor of a negative ratio is computed as −⌈∣n∣/d⌉-\lceil |n| / d \rceil, so the enclosure is correct for both signs. certified_dyadic_div rewrites a/b=(na2sb)/(nb2sa)a / b = (n_a 2^{s_b}) / (n_b 2^{s_a}) with the sign moved to the numerator, so it inherits the same bound. round_down and round_up are the same floor and ceiling at a smaller scale, so round_down(x,s)≤x≤round_up(x,s)\text{round\_down}(x, s) \le x \le \text{round\_up}(x, s).

Budget. The precision sequence is strictly increasing (each step adds at least 32 bits) and at most limit refinements are made, so every refinement loop that checks available() terminates.

Abort contract. pow5, pow10 with a negative exponent, round_positive_div with n<0n < 0 or d≤0d \le 0, exact_divide_by_power_of_ten with a negative shift and a non-zero coefficient, and dyadic constructors and roundings with a negative scale abort: these are programmer errors inside the cores, never reachable from user input. round_shift with a negative magnitude does not abort; it returns the value described above.

Alternatives rejected

  • Rounding via floating point. Converting to Double to round a ratio loses exactness beyond 53 bits; all helpers stay in BigInt.
  • Signed division with remainder. Truncating and flooring division differ for negative operands; sign-magnitude avoids the ambiguity.
  • A normalized CertifiedDyadic. Normalizing after every operation costs a trailing-zero scan; enclosures are compared with compare, which does not need canonical forms.
  • An unbounded power cache. Pathological exponents would retain huge BigInt values for the life of the process.

Boundaries

  • No floating-point formats, contexts or flags: the cores build them on these helpers.
  • No decimal string formatting and no special values (inf, nan) in split_decimal_string.
  • No public stability: the package is importable only inside Luna-Flow/floating.
  • The power caches are process-wide mutable state, the only state in the package; they never change a result.

Footnotes

  1. IEEE 754-2019, clause 4.3, defines the rounding-direction attributes; the integer case is the same definition with Z\mathbb{Z} as the set of representable numbers. ↩

  2. A. Ziv, “Fast evaluation of elementary mathematical functions with correctly rounded last bit”, ACM TOMS 17(3), 1991. ↩