binary design

binary implements IEEE 754 binary floating-point arithmetic at any precision. This page explains the mathematics behind it: the value set, the rounding functions and the error model they satisfy, how each operation decides the correctly rounded result from exact integer data, how the exponent range, tininess and the status flags are handled, why the IEEE remainder is exact, how decimal conversion and the elementary functions are certified, and why the fast integer kernels cannot change a result. The API reference lists the callable surface and the tutorial shows it in use.

Design goal

Every operation of binary returns the value that IEEE 754-2019 requires of a correctly rounded operation, ∘(f(x))\circ(f(x)) for the exact real f(x)f(x), together with exactly the IEEE status flags, for every precision pp from 1 to 2282^{28} bits and every exponent range up to ±(230−1)\pm(2^{30}-1). The same code serves two audiences: arbitrary-precision numerics that need dyadic values far beyond Double, and bit-exact emulation of binary16, binary32, binary64 and binary128 including subnormals, the five rounding directions and both tininess rules. There is no hidden state: precision, rounding and range travel in an immutable BinaryContext, and flags travel back as a value. The basic operations, conversions and pown meet this goal unconditionally; the certified elementary functions meet it for every value they return, with the budget failures and the one undetected family of exact results described under Certified elementary functions.

Mathematical background

Dyadic values and the stored triple

A finite Binary denotes the dyadic rational

x=(−1)s⋅c⋅2e,s∈{0,1}, c∈N, e∈Z,x = (-1)^s \cdot c \cdot 2^{e}, \qquad s \in \{0, 1\},\ c \in \mathbb{N},\ e \in \mathbb{Z},

where cc is a BinCoeff and ee is exponent2(). The representation is canonical: if c≠0c \ne 0 then cc is odd, and if c=0c = 0 then e=0e = 0. Every dyadic rational has exactly one such form (factor out 2ν2(c)2^{\nu_2(c)}), so two finite values are numerically equal exactly when their signs (for nonzero values), coefficients and exponents agree. The exponent of the leading bit is

top⁡(x)=⌊log⁡2∣x∣⌋=e+bits⁡(c)−1,\operatorname{top}(x) = \lfloor \log_2 |x| \rfloor = e + \operatorname{bits}(c) - 1,

and every comparison, range check and rounding decision below is phrased in terms of top⁡\operatorname{top} and bits⁡\operatorname{bits} instead of floating logarithms. Each value also carries a precision pp with bits⁡(c)≤p\operatorname{bits}(c) \le p; it records the format the value belongs to and is the default precision of plain operations on it.

Representation of a value

A Binary is a newtype over the internal enum BinRepr, so a value is one heap object (the constructors of an enum hold their scalar fields inline, and a newtype adds no object). The constructors are the forms of a finite value and the two kinds of non-finite value:

constructorholdswhen
Fin64sign, one word, ee, ppbits⁡(c)≤64\operatorname{bits}(c) \le 64; zero is word = 0, e=0e = 0
Fin128sign, two words, ee, pp65≤bits⁡(c)≤12865 \le \operatorname{bits}(c) \le 128
FinBigsign, a Coeff, ee, ppbits⁡(c)>128\operatorname{bits}(c) > 128
Infsign, pp±∞\pm\infty
NaNsign, signaling bit, payload, ppa NaN

The form of a finite value is a function of its coefficient, so the representation stays unique and the structural equality of the stored data is still the equality of the datum. A result of at most 128 bits costs one allocation, where a record of seven fields plus a coefficient object cost two; a result of more than 128 bits is the value object, a Coeff and its limb array. On the JavaScript target a coefficient is a host bigint and there is no word path, so the type has only FinBig, Inf and NaN. Only bin_repr_nonjs.mbt and bin_repr_js.mbt (the constructors and the accessors) and the _nonjs fast paths match on it; every other reader uses an accessor. Accessors that only need a test or a length (coefficient_is_zero, coefficient_bits, is_word, word_, is_pair, pair_high, pair_low) return scalars: a function on a hot path never returns an option of a scalar or a tuple, because both are heap objects. The general readers get the coefficient as a Coeff, which a value of at most 128 bits builds on demand.

The IEEE 754 binary formats

A binary interchange format with kk bits has a sign bit, a ww-bit biased exponent field EE and a (p−1)(p-1)-bit trailing significand field TT (IEEE 754-2019 clause 3.4).11 IEEE Std 754-2019, IEEE Standard for Floating-Point Arithmetic: clause 3 (formats), 4.3 (rounding-direction attributes), 5 (operations), 6 (infinities, NaNs, signed zero), 7 (default exception handling). With emax⁡=2w−1−1e_{\max} = 2^{w-1} - 1, the bias emax⁡e_{\max} and emin⁡=1−emax⁡e_{\min} = 1 - e_{\max}, an encoding means

v={(−1)s 2E−emax⁡(1+T 21−p)1≤E≤2w−2(normal),(−1)s 2emin⁡(0+T 21−p)E=0(subnormal or zero),(−1)s ∞E=2w−1, T=0,NaNE=2w−1, T≠0.v = \begin{cases} (-1)^s\, 2^{E - e_{\max}} \bigl(1 + T\, 2^{1-p}\bigr) & 1 \le E \le 2^w - 2 \quad\text{(normal)},\\ (-1)^s\, 2^{e_{\min}} \bigl(0 + T\, 2^{1-p}\bigr) & E = 0 \quad\text{(subnormal or zero)},\\ (-1)^s\, \infty & E = 2^w - 1,\ T = 0,\\ \mathrm{NaN} & E = 2^w - 1,\ T \ne 0. \end{cases}
Formatkkwwppemax⁡e_{\max}emin⁡e_{\min}largest Ω\Omegasmallest normalsmallest subnormal
binary161651115−1465504655042−142^{-14}2−242^{-24}
binary3232824127−126(2−2−23)2127(2-2^{-23})2^{127}2−1262^{-126}2−1492^{-149}
binary646411531023−1022(2−2−52)21023(2-2^{-52})2^{1023}2−10222^{-1022}2−10742^{-1074}
binary1281281511316383−16382(2−2−112)216383(2-2^{-112})2^{16383}2−163822^{-16382}2−164942^{-16494}

Forgetting the encoding, the finite values of the format are

F(p,emin⁡,emax⁡)={ M⋅2q:M∈Z, ∣M∣<2p, q≥emin⁡−p+1, ∣M∣2q<2emax⁡+1 }.F(p, e_{\min}, e_{\max}) = \{\, M \cdot 2^{q} : M \in \mathbb{Z},\ |M| < 2^{p},\ q \ge e_{\min} - p + 1,\ |M| 2^{q} < 2^{e_{\max}+1} \,\}.

A BinaryContext is exactly this triple plus a rounding direction and a tininess rule. Its emin⁡e_{\min} and emax⁡e_{\max} are leading-bit exponents, so a normal number has emin⁡≤top⁡(x)≤emax⁡e_{\min} \le \operatorname{top}(x) \le e_{\max}, and the grid below 2emin⁡2^{e_{\min}} has the fixed quantum

η=2emin⁡−p+1,\eta = 2^{e_{\min} - p + 1},

the smallest positive subnormal. Missing bounds are replaced by the implementation range ±(230−1)\pm(2^{30}-1), which is large enough that every exponent arithmetic step fits a 64-bit intermediate and every stored exponent an Int; binary_precision_max =228= 2^{28} keeps emin⁡−p+1e_{\min} - p + 1 in range too.

Rounding functions

For x∈Rx \in \mathbb{R} let x−=max⁡{y∈F:y≤x}x^- = \max\{y \in F : y \le x\} and x+=min⁡{y∈F:y≥x}x^+ = \min\{y \in F : y \ge x\}, extending FF by ±∞\pm\infty beyond ±Ω\pm\Omega for the moment. The six rounding directions of BinaryRoundingMode are the maps R→F∪{±∞}\mathbb{R} \to F \cup \{\pm\infty\}

RD⁡(x)=x−,RU⁡(x)=x+,RZ⁡(x)=sign⁡(x) ∣x∣−,RA⁡(x)=sign⁡(x) ∣x∣+,RNE⁡(x)=the nearer of x−,x+, the one with even M on a tie,RNA⁡(x)=the nearer of x−,x+, the one of larger magnitude on a tie,\begin{aligned} \operatorname{RD}(x) &= x^-, \qquad \operatorname{RU}(x) = x^+, \\ \operatorname{RZ}(x) &= \operatorname{sign}(x)\,|x|^-, \qquad \operatorname{RA}(x) = \operatorname{sign}(x)\,|x|^+, \\ \operatorname{RNE}(x) &= \text{the nearer of } x^-, x^+, \text{ the one with even } M \text{ on a tie}, \\ \operatorname{RNA}(x) &= \text{the nearer of } x^-, x^+, \text{ the one of larger magnitude on a tie}, \end{aligned}

where RA (round the magnitude up) is not an IEEE attribute: it is the GDA “round-up” mode that @lf_arith.RoundingMode shares with the decimal cores, and BinaryRoundingMode has no such variant. Two properties of every ∘\circ above carry most of the proofs on this page:

(R1)  x∈F  ⟹  ∘(x)=x,(R2)  x≤y  ⟹  ∘(x)≤∘(y).\text{(R1)}\ \ x \in F \implies \circ(x) = x, \qquad\qquad \text{(R2)}\ \ x \le y \implies \circ(x) \le \circ(y).

(R1) holds because x−=x+=xx^- = x^+ = x on FF. (R2) holds because each ∘(x)\circ(x) is one of the two neighbours of xx chosen by a rule that only moves from x−x^- to x+x^+ as xx increases through a cell [x−,x+][x^-, x^+].

The standard error model

Let u=2−pu = 2^{-p} be the unit roundoff. Take xx with 2t≤∣x∣<2t+12^{t} \le |x| < 2^{t+1}, t≥emin⁡t \ge e_{\min} (the normal range) and ∣x∣|x| below the overflow threshold of the rounding direction (otherwise the result is an infinity and no relative bound holds). The points of FF in that binade are spaced 2t−p+12^{t-p+1} apart, and 2t+12^{t+1} belongs to FF or is the overflow point, so

∣RN⁡(x)−x∣≤12 2t−p+1=2t−p≤2−p∣x∣=u∣x∣,∣RD⁡(x)−x∣, ∣RU⁡(x)−x∣<2t−p+1≤2u∣x∣,\begin{aligned} |\operatorname{RN}(x) - x| &\le \tfrac12\, 2^{t-p+1} = 2^{t-p} \le 2^{-p} |x| = u|x|, \\ |\operatorname{RD}(x) - x|,\ |\operatorname{RU}(x) - x| &< 2^{t-p+1} \le 2u|x|, \end{aligned}

where RN is RNE or RNA. Writing ∘(x)=x(1+δ)\circ(x) = x(1 + \delta) gives the standard model

fl⁡(a∘b)=(a∘b)(1+δ),∣δ∣≤u (nearest),∣δ∣<2u (directed).\operatorname{fl}(a \circ b) = (a \circ b)(1 + \delta), \qquad |\delta| \le u \ \text{(nearest)}, \quad |\delta| < 2u \ \text{(directed)}.

The nearest bound sharpens to ∣δ∣≤u/(1+u)|\delta| \le u/(1+u) by dividing by ∣∘(x)∣|\circ(x)| instead of ∣x∣|x|.22 N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM 2002, §2.2; D. Goldberg, “What every computer scientist should know about floating-point arithmetic”, ACM Computing Surveys 23(1), 1991. Below 2emin⁡2^{e_{\min}} the spacing is the constant η\eta, so the error is absolute: ∣RN⁡(x)−x∣≤η/2|\operatorname{RN}(x) - x| \le \eta/2 and ∣RD⁡(x)−x∣<η|\operatorname{RD}(x) - x| < \eta. Both regimes together give the model with an underflow term,

fl⁡(a∘b)=(a∘b)(1+δ)+ϵ,∣δ∣≤u,∣ϵ∣≤η2,δϵ=0,\operatorname{fl}(a \circ b) = (a \circ b)(1 + \delta) + \epsilon, \qquad |\delta| \le u,\quad |\epsilon| \le \tfrac{\eta}{2},\quad \delta\epsilon = 0,

for nearest rounding (2u2u and η\eta for directed rounding). Addition and subtraction never need ϵ\epsilon: if a,b∈Fa, b \in F then both are integer multiples of η\eta, so is a±ba \pm b, and a multiple of η\eta below 2emin⁡2^{e_{\min}} lies in FF. Hence a subnormal sum is exact, which is why gradual underflow keeps a−b=0  ⟺  a=ba - b = 0 \iff a = b.33 J.-M. Muller et al., Handbook of Floating-Point Arithmetic, 2nd ed., Birkhäuser 2018, §2.1 and §4.3.

Correct rounding is a stronger property than the model: the result is the one point ∘(f(x))\circ(f(x)), not merely some point within uu. Every value binary returns is that point, so the model above holds for every operation, including the elementary functions.

Design decisions

Round once from exact data

Problem. A result must equal ∘(r)\circ(r) for the exact real rr, but rr may need far more bits than pp (a product of two pp-bit numbers has 2p2p), or infinitely many (a quotient, a square root, exe^x).

Options. Compute in a wider format and round again, as hardware without FMA does; or keep a fixed number of guard bits; or decide the rounding from exact information.

Choice. Every operation computes an exact description of rr and calls one finalizer. For dyadic results (sum, difference, product, fma, scaleb, remainder, conversion) the description is the exact integer magnitude mm and exponent ee with r=±m2er = \pm m 2^{e}. The finalizer picks the shift

σ=max⁡(bits⁡(m)−p, (emin⁡−p+1)−e, 0),\sigma = \max\bigl(\operatorname{bits}(m) - p,\ (e_{\min} - p + 1) - e,\ 0\bigr),

the larger of the precision shift and the shift onto the subnormal grid, and splits m2−σ=q+fm 2^{-\sigma} = q + f with q=⌊m2−σ⌋q = \lfloor m 2^{-\sigma} \rfloor and 0≤f<10 \le f < 1 into three items of data:

q,g=[ f≥12 ]=bit σ−1 of m,t=[ f∉{0,12} ]=[ ν2(m)<σ−1 ].q, \qquad g = [\,f \ge \tfrac12\,] = \text{bit } \sigma - 1 \text{ of } m, \qquad t = [\,f \notin \{0, \tfrac12\}\,] = [\,\nu_2(m) < \sigma - 1\,].

These are the classical round and sticky bits, read from the coefficient by test_bit and ctz without building any shifted copy. They determine every rounding direction: with q0q_0 the last bit of qq,

Directionincrement qq when
RNEg∧(t∨q0)g \wedge (t \vee q_0)
RNAgg
RZnever
RU(g∨t)∧s=0(g \vee t) \wedge s = 0
RD(g∨t)∧s=1(g \vee t) \wedge s = 1
RAg∨tg \vee t

Derivation. f>12  ⟺  g∧tf > \frac12 \iff g \wedge t, f=12  ⟺  g∧¬tf = \frac12 \iff g \wedge \neg t, and f>0  ⟺  g∨tf > 0 \iff g \vee t. RNE rounds the magnitude up when f>12f > \frac12, or when f=12f = \frac12 and qq is odd; that is (g∧t)∨(g∧¬t∧q0)=g∧(t∨q0)(g \wedge t) \vee (g \wedge \neg t \wedge q_0) = g \wedge (t \vee q_0). The directed rows round the magnitude up exactly when f>0f > 0 and the direction points away from zero for the sign ss. Inexactness is g∨tg \vee t.

Why. Because σ\sigma already includes the subnormal shift, a tiny result is rounded once, directly from mm, to the grid ηZ\eta \mathbb{Z}. Rounding first to pp bits and then to the subnormal grid would be a double rounding: a value just above a midpoint of the coarse grid can be pushed onto that midpoint by the first rounding and then rounded the wrong way by the second. A carry out of qq (when q+1=2pq + 1 = 2^p) only raises top⁡\operatorname{top} by one; the result is re-normalized and the overflow test below is applied to the rounded value.

The three paths of the finalizer, and why the normalization chain is skipped. binary_round_dyadic takes one of three paths. (1) Exact exit: if bits⁡(m)≤p\operatorname{bits}(m) \le p and emin⁡≤top⁡≤emax⁡e_{\min} \le \operatorname{top} \le e_{\max} (the context range, clamped to the implementation range), then r=m2er = m 2^{e} is representable: e≥emin⁡−p+1e \ge e_{\min} - p + 1, so the shift σ\sigma is 00, nothing is rounded and no flag is raised; this holds for bounded and unbounded contexts alike. (2) Precision path: if the shift onto the subnormal grid is not larger than the precision shift, the precision rounding already uses the final σ\sigma, so its result is the final result and the rounding is done once; its top bit is also the “rounded top” that the tininess rule after rounding and the overflow test need. (3) Range path: otherwise the value is split again at the range shift, and the precision rounding is kept only to supply the rounded top. In all three paths the stored value is built by binary_finite_in_range: the coefficient has at most pp bits (a carry out of qq gives a power of two, which is even and is stripped to 11), its top bit is at least emin⁡−p+1e_{\min} - p + 1 and at most emax⁡e_{\max} (overflow is tested first), so the general normalization has nothing left to do except stripping trailing zeros: the implementation-range underflow, the re-rounding of excess bits and the overflow test of normalize_finite cannot fire. The tests keep copies of the old core and compare value and flags on random corpora and at the exponent limits.

Finishing a wide result in place

Problem. The plain add, mul, div and sqrt of operands wider than one word end in a rounding to nearest even. Done on the whole coefficient, it copied the kept bits into a new array, incremented it, and shifted it a second time to strip the trailing zero bits: three passes over the result and an array of the same size each time.

Choice. The fast path hands the finisher the magnitude as a limb array WW (little-endian, the top limbs may be zero), the exponent of bit 0, the precision, a sticky flag and the rounding direction. With b=bits⁡(W)b = \operatorname{bits}(W) and σ=b−p\sigma = b - p, the finisher reads the round bit, the last kept bit and (only when the decision needs it, and stopping at the first non-zero limb) the lower bits, decides the increment with the table above, and finds the position qq of the lowest set bit of the rounded value without forming it. Let K=⌊W/2σ⌋K = \lfloor W / 2^{\sigma} \rfloor be the kept bits.

  • No increment: qq is the position of the lowest set bit of WW at or above σ\sigma, and the coefficient is W≫qW \gg q.
  • Increment: K+1K + 1 has as many trailing zeros as KK has trailing ones, say tt, and (K+1)≫t=(K≫t)∣1(K + 1) \gg t = (K \gg t) \mid 1 because bit tt of KK is zero. So qq is the position of the lowest zero bit of WW at or above σ\sigma (at most bb, since bit bb is zero) and the coefficient is (W≫q)∣1(W \gg q) \mid 1; when every kept bit is set, q=bq = b and the coefficient is 11, which is 2p2^p stripped. No carry is ever propagated.

The coefficient is then W≫qW \gg q written into the same array: the destination index never exceeds the source index, so one forward loop suffices, and the result keeps the array. The sticky flag stands for “the exact value is WW plus an amount in (0,1)(0, 1) units of bit 0”. It is allowed only when b>pb > p, and then it changes the decision only through tt, because the discarded part d+εd + \varepsilon with integer d<2σd < 2^{\sigma} and 0<ε<10 < \varepsilon < 1 is below, at or above the half 2σ−12^{\sigma - 1} exactly as dd is, except that d=2σ−1d = 2^{\sigma - 1} is above it. This is what lets a caller truncate a quotient, a square root or an aligned sum at p+2p + 2 bits and pass the rest as one bit.

Why. The result array is the only allocation besides the value itself, and the rounding is one probe of a few limbs plus one shifting loop. The finisher takes the direction as a parameter so that the contextual operations can use it; the plain operators pass round to nearest even. The tests keep the previous finisher and the contextual rounding as references and compare value, sign, exponent and precision bit for bit in every direction, on ties, on all-ones carries and on cancelled leading limbs.

Who owns the array. The product (exact or short), the scaled and the short quotient and the packed square root of the coefficient kernel return a heap coefficient whose array nothing else refers to (the contract is stated in the kernel design page), so the fast paths of mul, div and sqrt hand it to the finisher as it is and it is rounded in place, with no copy. A coefficient of at most 128 bits has no array and takes the copying path; so does the rare division through a general quotient and remainder, whose array is not covered by the contract. The tests run each operation twice on the same operands, on a value with itself and on a copy of it, and check that no operand word changed.

Division from quotient and remainder

Problem. a/ba/b with a=ca2eaa = c_a 2^{e_a}, b=cb2ebb = c_b 2^{e_b} is a rational N/D⋅2eN/D \cdot 2^{e} (N=caN = c_a, D=cbD = c_b, e=ea−ebe = e_a - e_b) whose binary expansion is usually infinite.

Choice. First the exact leading exponent: with k=bits⁡(N)−bits⁡(D)k = \operatorname{bits}(N) - \operatorname{bits}(D), ⌊log⁡2(N/D)⌋\lfloor \log_2 (N/D) \rfloor is kk if N≥D2kN \ge D 2^{k} and k−1k - 1 otherwise, one integer comparison. That fixes the target exponent τ=max⁡(top⁡−p+1, emin⁡−p+1)\tau = \max(\operatorname{top} - p + 1,\ e_{\min} - p + 1), and then one integer division

N2e−τ=qD+r,0≤r<DN 2^{e - \tau} = q D + r, \qquad 0 \le r < D

gives qq directly, and the remainder gives the rounding data: f=r/Df = r/D, so

g=[ 2r≥D ],t=[ r≠0∧2r≠D ].g = [\,2r \ge D\,], \qquad t = [\,r \ne 0 \wedge 2r \ne D\,].

No approximation of N/DN/D is involved; the rounding is decided by the sign of 2r−D2r - D. When e−τ<0e - \tau < 0 the shift is moved to the denominator, and a quotient below one unit is decided by comparing 2N2N with D2τ−eD 2^{\tau - e} without forming it.

Square root from an integer root and a midpoint test

Problem. c2e\sqrt{c 2^{e}} is irrational unless c2ec 2^{e} is a square.

Choice. The leading exponent is ⌊top⁡(x)/2⌋\lfloor \operatorname{top}(x)/2 \rfloor (floor division), which fixes τ\tau as above. Write the radicand as X=c 2e−2τX = c\, 2^{e - 2\tau}, so x=X 2τ\sqrt{x} = \sqrt{X}\, 2^{\tau}. An exact integer square root gives s=⌊X⌋s = \lfloor \sqrt{X} \rfloor with remainder X−s2X - s^2; the root is exact iff the remainder is zero. Otherwise the rounding data come from the midpoint s+12s + \frac12:

X≷s+12  ⟺  X≷(s+12)2  ⟺  4X≷(2s+1)2,\sqrt{X} \gtrless s + \tfrac12 \iff X \gtrless \bigl(s + \tfrac12\bigr)^2 \iff 4X \gtrless (2s+1)^2,

an exact comparison of integers (with the power of two moved to the other side when XX is fractional). So g=[4X≥(2s+1)2]g = [4X \ge (2s+1)^2] and t=¬exact∧[4X≠(2s+1)2]t = \neg\text{exact} \wedge [4X \ne (2s+1)^2]. When XX is an integer the right side is odd and the left even, so the root is never exactly a midpoint; this is the classical fact that x\sqrt{x} of a pp-bit number is never a (p+1)(p+1)-bit midpoint.44 Muller et al., Handbook of Floating-Point Arithmetic, §5.3 and §7.6. The equality branch is still kept, because an operand with more bits than the context precision can make X\sqrt{X} an exact midpoint (for example 9/4=3/2\sqrt{9/4} = 3/2 rounded to one bit).

Exponent range, overflow and underflow

Overflow is decided on the rounded value: if the rounded result has top⁡>emax⁡\operatorname{top} > e_{\max}, the operation overflows, which is IEEE 754’s “after rounding” rule (clause 7.4). From the rounding table this happens at the thresholds

RNE, RNA:∣r∣≥2emax⁡(2−2−p)=Ω+12ulp⁡(Ω),RA, and RU for r>0, RD for r<0:∣r∣>Ω,RZ, and RU for r<0, RD for r>0:never to ∞,\begin{aligned} \text{RNE, RNA:}\quad & |r| \ge 2^{e_{\max}}\bigl(2 - 2^{-p}\bigr) = \Omega + \tfrac12 \operatorname{ulp}(\Omega), \\ \text{RA, and RU for } r>0, \text{ RD for } r<0:\quad & |r| > \Omega, \\ \text{RZ, and RU for } r<0, \text{ RD for } r>0:\quad & \text{never to } \infty, \end{aligned}

because a value in (Ω,Ω+12ulp⁡)(\Omega, \Omega + \frac12\operatorname{ulp}) rounds to nearest down to Ω\Omega, while the tie Ω+12ulp⁡\Omega + \frac12\operatorname{ulp} goes to the even neighbour 2emax⁡+12^{e_{\max}+1}, which lies outside FF. An overflowing result is ±∞\pm\infty for the first two groups and ±Ω\pm\Omega for the third, always with overflow and inexact. In binary16, Ω=65504\Omega = 65504 and 12ulp⁡(Ω)=16\frac12\operatorname{ulp}(\Omega) = 16:

///|
test "binary16 overflow threshold under nearest rounding" {
  let ctx = @binary.BinaryContext::binary16()
  let (below, below_flags) = @binary.Binary::from_int(65519).apply_ctx(ctx)
  let (at, at_flags) = @binary.Binary::from_int(65520).apply_ctx(ctx)
  inspect("\{below} \{below_flags.overflow()}", content="2047p5 false")
  inspect("\{at} \{at_flags.overflow()}", content="inf true")
}

Tininess. A nonzero result is tiny when it lies strictly between ±2emin⁡\pm 2^{e_{\min}}. IEEE 754-2019 (clause 7.5) allows two readings, and TininessDetection selects one:

before rounding: ∣r∣<2emin⁡;after rounding: ∣∘p,∞(r)∣<2emin⁡,\text{before rounding: } |r| < 2^{e_{\min}}; \qquad \text{after rounding: } |\circ_{p,\infty}(r)| < 2^{e_{\min}},

where ∘p,∞\circ_{p,\infty} rounds to pp bits with an unbounded exponent range. The finalizer computes top⁡(r)\operatorname{top}(r) exactly and, for the after-rounding rule, a second split of the same magnitude at the precision shift alone. The two readings differ only for rr just below 2emin⁡2^{e_{\min}} that rounds up to it at pp bits: for binary16, r=2−14−2−27r = 2^{-14} - 2^{-27} is tiny before rounding but rounds at 11 bits to 2−142^{-14}, which is not tiny.

Underflow flag. Under default exception handling the underflow flag is raised for a tiny result only when it is also inexact. The finalizer returns no flags at all for an exact result, so an exact subnormal (for example any subnormal difference, as shown above) raises nothing. The binary16 product 2−14×(1−2−11)2^{-14} \times (1 - 2^{-11}) shows the full rule: the exact value 2−14−2−252^{-14} - 2^{-25} is tiny under both readings, lies halfway between two subnormals of spacing 2−242^{-24}, rounds to the even neighbour 2−142^{-14}, the smallest normal, and raises underflow and inexact, although the encoded result 0x0400 is normal.

///|
test "underflow is raised for a tiny inexact result that rounds to normal" {
  let format = @binary.BinaryInterchangeFormat::Binary16
  let smallest_normal = @binary.BinaryInterchange::from_hex("0400", format)
    .unwrap()
    .to_binary()
  let below_one = @binary.BinaryInterchange::from_hex("3BFF", format)
    .unwrap()
    .to_binary()
  let (product, flags) = smallest_normal.mul_ctx(below_one, format.context())
  inspect(product.to_interchange(format).0.to_hex(), content="0400")
  inspect("\{flags.underflow()} \{flags.inexact()}", content="true true")
}

Far below the range. A result certainly smaller than η/2\eta/2 in magnitude (decided from exponent bounds without forming it, for example 2−109⋅2−1092^{-10^9} \cdot 2^{-10^9}) rounds to ±0\pm 0 or ±η\pm\eta according to the direction, with underflow and inexact. A result certainly above the range goes to the overflow result.

Exact results in the subnormal range. An elementary function whose exact result is the dyadic m⋅2nm \cdot 2^{n} (2n2^{n} for exp2 of an integer, the exact power of pow with a dyadic result) passes it to the finalizer as the pair (m,n)(m, n). It does not build a Binary first: a Binary made from (1,n)(1, n) at one bit has its smallest value at 2emin⁡2^{e_{\min}}, so 2n2^{n} with n<emin⁡n < e_{\min} was flushed to zero before any context could round it, although it is exactly representable at p≥2p \ge 2. The after-rounding rule uses ∘p,∞\circ_{p,\infty} with no exponent range at all, not an unbounded context, which still has gradual underflow at the implementation limit 2emin⁡2^{e_{\min}}.

One layer for the new recommended functions. The defects of the range audit (an exact power of two flushed by a one-bit Binary::make, a shortcut returning before a signaling NaN is seen, an unbounded context used as a range-free rounding) were each a pattern that a function could write again. exp2m1, exp10m1, log2p1 and log10p1, and the families that follow in #235, therefore take four decisions from one internal file (elementary_range.mbt): the NaN and pole results (binary_nan_unary, binary_pole_result, a signaling NaN first); an exact result rounded as a dyadic by the finalizer, never built as a Binary (binary_integer_result, binary_pow2_minus_one_integer); the overflow decision of bx−1b^x - 1 from certified bounds of log⁡2b\log_2 b (binary_positive_exp_minus_one_overflow, including the window xlog⁡2b∈[emax⁡+1,emax⁡+2)x \log_2 b \in [e_{\max} + 1, e_{\max} + 2) and, for base 2, x>emax⁡+1x > e_{\max} + 1 with x−(emax⁡+1)≥2−(emax⁡+1)+1x - (e_{\max} + 1) \ge 2^{-(e_{\max} + 1) + 1}); and one Ziv driver (binary_ziv_round). For an integer nn with n≥p+2n \ge p + 2 the value 2n−12^n - 1 lies in the open interval between the midpoint under 2n2^n and 2n2^n, where every value rounds alike in each direction, so a representative of the same binade stands for it and the huge integer is never formed; below p+2p + 2 bits it is exact or a tie and is rounded as it is.

rsqrt, compound and powr (second family of #235) add no new rounding logic: each reduces to an operation that already owns the exact cases and the range decision, after the special values of §9.2.1. 1/x1/\sqrt{x} is rootn(x, -2), xyx^y for x>0x > 0 is pow, and (1+x)n(1 + x)^n is pown of the exact sum 1+x1 + x whenever that sum fits in 2262^{26} bits. The one decision of its own is the tiny rule of compound: for ∣nx∣<2−(p+9)|n x| < 2^{-(p + 9)} the exact value is 1+δ1 + \delta with ∣δ∣<2−(p+8)|\delta| < 2^{-(p+8)}, far inside the window around 11 bounded by the breakpoints 1−2−(p+1)1 - 2^{-(p+1)} and 1+2−p1 + 2^{-p}, so the result is 11 or its neighbour by direction alone and equals the rounding of the surrogate 1±2−(p+3)1 \pm 2^{-(p+3)}, which binary_round_dyadic takes through the same finalizer as any exact value.

asinpi, acospi, atanpi and atan2pi (third and last family of #235) are asin⁡(x)/π\operatorname{asin}(x)/\pi, acos⁡(x)/π\operatorname{acos}(x)/\pi, atan⁡(x)/π\operatorname{atan}(x)/\pi and atan2⁡(y,x)/π\operatorname{atan2}(y, x)/\pi: the existing certified enclosures of the angle divided by a certified enclosure of π\pi, rounded by the Ziv driver. By Niven’s theorem the only exact (dyadic) values are the constants of §9.2.1 and atanPi⁡(±1)=±1/4\operatorname{atanPi}(\pm 1) = \pm 1/4, atan2Pi⁡(±a,±a)=±1/4,±3/4\operatorname{atan2Pi}(\pm a, \pm a) = \pm 1/4, \pm 3/4, which are rounded as dyadics; 1/61/6, 1/31/3 and 2/32/3 are rational but not breakpoints, so the loop terminates on them. The range hazards are anchors, decided before the loop by binary_tiny_argument_result from a certified distance: atanPi⁡(x)=±(1/2−δ)\operatorname{atanPi}(x) = \pm(1/2 - \delta) with δ<2−t\delta < 2^{-t} for ∣x∣≥2t|x| \ge 2^t, t≥p+8t \ge p + 8; acosPi⁡(x)=1/2∓δ\operatorname{acosPi}(x) = 1/2 \mp \delta with δ<∣x∣/2\delta < |x|/2 for a tiny ∣x∣|x|; and atan2Pi⁡(y,x)\operatorname{atan2Pi}(y, x) at ±1/2\pm 1/2 (D≥p+8D \ge p + 8) and ±1\pm 1 (D≤−(p+8)D \le -(p + 8), x<0x < 0), where DD is the difference of the leading-bit exponents, so that the ratio y/xy/x (whose exponent can be ±231\pm 2^{31}) is never formed. For x>0x > 0 and a ratio so small that t/πt/\pi lies below a quarter of the smallest subnormal the result is the tiny nonzero result of the direction. Everything else is the enclosure atan⁡(t)/π\operatorname{atan}(t)/\pi (or 1−atan⁡(t)/π1 - \operatorname{atan}(t)/\pi) at a working precision above the operands’.

Handover: the range layer and how to add a function

The recommended functions of §9.2 were added in three families on one layer (library/src/binary/elementary_range.mbt) and the helpers it builds on (binary_round_dyadic and binary_round_precision_only in context_arithmetic.mbt; binary_certified_inexact_target_rounding, binary_inexact_inner_endpoint and binary_tiny_argument_result in elementary_certified.mbt). Their purpose is to make the defect class of the range audit (#271 to #316) impossible to write again: Binary::make(c, e, w) at a width ww flushes every value below 2emin⁡−(w−1)2^{e_{\min} - (w - 1)}, so a result or a helper value must never be built that way; exact results are rounded as dyadics, and a value that clusters at a representable anchor is decided by its certified distance to it.

The layer exposes (all internal):

nameuse
binary_nan_unary(value, context)NaN operand: quiet NaN, invalid for a signaling one; call first
binary_pole_result(negative, context)±∞\pm\infty with divideByZero
binary_integer_result(n, context)an integer result rounded as a dyadic
binary_pow2_minus_one_integer(n, context)2n−12^n - 1 for any integer n≠0n \ne 0
binary_saturated_minus_one(context)−1+ε-1 + \varepsilon decided by direction
binary_positive_exp_minus_one_overflow(...)certain overflow of bx−1b^x - 1 from certified log⁡2b\log_2 b
binary_ziv_round(operation, context, bounds_at)the Ziv driver: bounds_at(work) returns a certified enclosure of an inexact result
binary_round_dyadic(negative, coefficient, exponent, context)an exact value, both tininess rules, overflow, subnormals
binary_round_precision_only(...)the pp-bit rounding with no range (for after-rounding tininess)
binary_tiny_argument_result(anchor, above, scale, context)a result within 2scale2^{scale} of a representable anchor, above or below it, decided by direction
binary_tiny_nonzero_result(negative, context)a nonzero result below a quarter of the smallest subnormal

To add a function: (1) write the special-value table of §9.2.1 and Table 9.1 from the PDF text and quote it in the file header and the tests; (2) check a NaN first (binary_nan_unary), a signaling NaN before any shortcut; (3) list the exact results (by Niven-type arguments or direct algebra) and return them through binary_round_dyadic; (4) find the anchors and the ranges that cluster (a tiny or huge argument, an extreme ratio) and decide them with binary_tiny_argument_result with a proved bound on the distance; (5) write the enclosure for binary_ziv_round, with the working precision at least the operand precision plus 16 and the operation known to be inexact; (6) add the try_*_ctx, *_ctx and plain forms, the BinaryChecked wrappers and the mpfr_expr operation; (7) test against a model that does not use the code under test (an exact rational, an anchor table, the result at precision p+150p + 150), at the subnormal limit of the implementation and of a few bounded formats, in every rounding direction and both tininess modes; (8) add the MPFR operation to tools/generate_mpfr_random_oracle.c as a new family appended after the existing operations (the rows of older families stay byte for byte), generate range boundary rows in tools/range_boundary_rows.py, run 1,000,000 native and 100,000 cases on each other backend and the boundary sweep, and add a few boundary rows to testdata/binary/random-regressions.txt; (9) document the function, its evidence and, for a defect of the oracle, the finding.

The oracle is not the specification. Findings about MPFR 4.2.2 (Homebrew bottle, arm64) made while doing this, each documented in testdata/binary/README.md: mpfr_sqrt returns a wrong ternary value or a result on the wrong side for some odd-exponent operands near the output precision (the generator checks every sqrt row with an exact product and draws again); mpfr_compound_si is not correctly rounded for a negative nn in the directed modes nor near the ends of the exponent range (the generator rounds the exact rational with mpfr_set_q; the library was right in every one of 2,017 rows proved by independent rational arithmetic); mpfr_rec_sqrt(-0) is +∞+\infty by MPFR’s own convention where §9.2.1 says −∞-\infty (the expected value follows the standard); mpfr_atan2pi takes time that grows with the exponent difference of its operands (not a wrong answer: rows over 100,000 binades apart are not generated).

Signed zeros and NaNs

An exact zero sum a+b=0a + b = 0 with a,ba, b of opposite sign is +0+0 in every direction except RD, where it is −0-0; (−0)+(−0)=−0(-0) + (-0) = -0 (clause 6.3). Products and quotients take the exclusive-or of the signs. A NaN operand yields the first NaN operand, quieted, with its sign and payload (clause 6.2.3 allows any input NaN), and invalid_operation is raised exactly when an operand is a signaling NaN or the operation is invalid on its own (∞−∞\infty - \infty, 0⋅∞0 \cdot \infty, 0/00/0, ∞/∞\infty/\infty, x<0\sqrt{x<0}, remainder⁡(∞,y)\operatorname{remainder}(\infty, y), remainder⁡(x,0)\operatorname{remainder}(x, 0)). Flags are values: combine is the bitwise OR, so the flags of a computation form a commutative idempotent monoid and can be accumulated in any order, which a global sticky register cannot offer to concurrent code.

The elementary functions take the signs of their special values from IEEE 754-2019 §9.2.1, which reads the sign of a zero operand: for example atan2⁡(±0,−0)=±π\operatorname{atan2}(\pm 0, -0) = \pm\pi but atan2⁡(±0,+0)=±0\operatorname{atan2}(\pm 0, +0) = \pm 0, tanpi⁡(n)\operatorname{tanpi}(n) has the sign of sinpi⁡(n)/cospi⁡(n)\operatorname{sinpi}(n)/\operatorname{cospi}(n), and (−0)y(-0)^y and (−∞)y(-\infty)^y are negative exactly for an odd integral yy.

Classes of a value

IEEE 754-2019 clause 5.7.2 defines class(x) with ten values, which the def package spells as IeeeClass. Zeros, infinities and NaNs are read from the stored class and sign (a signaling NaN is the flag the value keeps). The normal/subnormal split is the one rule of clause 3.4: a nonzero finite xx is normal when 2emin⁡≤∣x∣2^{e_{\min}} \le |x|, that is when the exponent of its leading bit is at least emin⁡e_{\min}, and subnormal otherwise. A Binary stores no emin⁡e_{\min} (it has only a precision), so class_of, is_normal and is_subnormal take the BinaryContext, the same way Decimal takes a DecimalContext. The leading-bit exponent is computed from the coefficient’s bit length and the exponent, so the test is exact and independent of the precision; no rounding happens and no flag is raised. is_finite, is_infinite and is_nan need no context. class_of is a total function: the ten classes partition every Binary, and Decimal::class_name is the text of the same partition for Decimal.

Format conversion

convert_format is apply_ctx in the destination format’s context, so the conversion inherits the one rounding step of the dyadic finalizer: a destination with at least the precision and range of the source is exact (the value needs at most psource≤pdestinationp_{\text{source}} \le p_{\text{destination}} bits and its exponent is inside the wider range), and a narrower one rounds once, with the flags of clause 7. The only extra step is the payload of a NaN: apply_ctx keeps the whole payload of a Binary only for a context of at least the same precision (a NaN of precision pp has p−2p - 2 payload bits, so every operation and constructor that delivers a NaN at another precision truncates, 6.2.3), and a format holds p−2p - 2 payload bits below the quiet bit, so the payload is masked to its low bits, which makes the result the value that decoding to_interchange returns and keeps the clause 6.2.3 round trip (narrower to wider to the same narrower format) exact. The independent oracle is Berkeley TestFloat: all twelve pairs among binary16, 32, 64 and 128 in the gate, five rounding directions and both tininess rules for the narrowing pairs; a widening pair does not round, so it is one task.

Far-apart operands in addition

Problem. 2109+2−1092^{10^9} + 2^{-10^9} is exact as a dyadic number, but forming it needs a two-billion-bit coefficient.

Choice. When the leading exponents differ by more than p+3p + 3, the sum is formed on the grid with unit υ=2e(high)−p−3\upsilon = 2^{e(\text{high}) - p - 3}, where e(high)e(\text{high}) is the exponent of the last bit of the larger operand, so υ≤2top⁡(high)−p−3\upsilon \le 2^{\operatorname{top}(\text{high}) - p - 3}. The larger operand HυH\upsilon is exact on that grid; of the smaller operand only the integer part LL of its value in units υ\upsilon enters, and if anything below υ\upsilon was discarded the magnitude becomes 2(H±L)+12(H \pm L) + 1 (for subtraction 2(H−L−1)+12(H - L - 1) + 1) in units of υ/2\upsilon/2, that is, one sticky bit at the half unit.

Why it is exact for rounding. The result has top⁡≥top⁡(high)−1\operatorname{top} \ge \operatorname{top}(\text{high}) - 1, because the smaller operand is below 2top⁡(high)−p−22^{\operatorname{top}(\text{high}) - p - 2}. The last retained bit of the rounded result therefore has position at least top⁡(high)−p\operatorname{top}(\text{high}) - p (more on the subnormal grid), and its round bit at least top⁡(high)−p−1\operatorname{top}(\text{high}) - p - 1. The true sum and the substitute both lie strictly inside the same open interval ((H±L)υ,(H±L+1)υ)\bigl((H \pm L)\upsilon, (H \pm L + 1)\upsilon\bigr) (or are equal when nothing was discarded), and that interval lies between two consecutive multiples of υ≤2top⁡(high)−p−3\upsilon \le 2^{\operatorname{top}(\text{high}) - p - 3}, at least two bit positions below the round bit. So qq and gg agree, and tt is set in both cases exactly when something nonzero was discarded. The argument does not need the larger operand to have at most pp bits. For subtraction, H−(L+ε)=(H−L−1)+(1−ε)H - (L + \varepsilon) = (H - L - 1) + (1 - \varepsilon) with 0<1−ε<10 < 1 - \varepsilon < 1, so the same substitution applies to the borrowed form. The complete argument, including the subnormal shift, is in the attachment below.

One aligned pass for the sum of wide operands

Problem. The plain add of two coefficients wider than one word aligned each operand with a shift into a new array, added or compared and subtracted into a third, and then rounded: about ten passes over arrays of the size of the sum and six allocations, although the result needs pp bits.

Choice. Let XX be the operand with the larger top bit tt and YY the other, eX,eYe_X, e_Y the exponents of their lowest bits, and K=p+3K = p + 3. The sum is formed in a window of n=⌊(t−L)/64⌋+1n = \lfloor (t - L) / 64 \rfloor + 1 limbs whose bit 0 has weight 2L2^{L}, with

L=max⁡(min⁡(eX,eY), t−K).L = \max\bigl(\min(e_X, e_Y),\ t - K\bigr).

So n≤⌊(p+3)/64⌋+1n \le \lfloor (p + 3) / 64 \rfloor + 1, whatever the exponent gap. One loop over the limbs reads both operands through their shifts (the word and bit shift are computed once) and writes X±YX \pm Y once. XX is never cut (eX≥t−p>t−Ke_X \ge t - p > t - K). When YY reaches below the window, its dropped part is non-zero, because stored coefficients are odd (bit 0 of YY is dropped), and that is the sticky flag; when YY lies entirely below, none of its limbs is read. For a subtraction with a cut operand the loop starts with a borrow of one: ∣X∣−∣Y∣=(X−Yt−1)+(1−f)|X| - |Y| = (X - Y_t - 1) + (1 - f) with YtY_t the integer part and 0<f<10 < f < 1, as in the previous section. The window then holds the exact result, or a truncated one with the sticky flag, which the finisher of the previous section rounds in place.

Why the window is enough. If YY is cut, then eY<t−Ke_Y < t - K, so its top is below t−K+p=t−3t - K + p = t - 3 and the gap between the tops is at least 44. Then for an addition W≥2K−1W \ge 2^{K-1} has at least p+3p + 3 bits, and for a subtraction ∣X∣−∣Y∣>2t−1−2t−4≥2t−2|X| - |Y| > 2^{t-1} - 2^{t-4} \ge 2^{t-2}, so W=X−Yt−1W = X - Y_t - 1 has at least K−1=p+2K - 1 = p + 2 bits. By the argument of the finisher (the discarded part is d+εd + \varepsilon with integer dd and 0<ε<10 < \varepsilon < 1), p+1p + 1 bits and the sticky flag decide every rounding direction. If YY is not cut the result is exact. When the tops differ by at most one, the exact difference fits the window (min⁡(eX,eY)≥t−1−p\min(e_X, e_Y) \ge t - 1 - p), and any number of leading limbs may cancel: the finisher scans down to the top limb. For equal tops the difference is formed as left−right\text{left} - \text{right} and negated in place when the final borrow is set, so no comparison pass is needed; an all-zero window is the exact zero, which the general path signs.

Boundary. The operands must satisfy the same range test as the other coefficient paths; the former limit on the exponent gap is gone, because a far operand costs only the sticky flag. The tests keep the previous path and compare bit for bit with it and with add_ctx and sub_ctx, in the sizes, gaps, cancellations and ties listed in the pull request.

Fused multiply-add

fma_ctx forms the product cxcy2ex+eyc_x c_y 2^{e_x + e_y} exactly as a value whose precision equals its own bit length, and passes it to the addition finalizer, so xy+zx y + z is rounded once (clause 5.4.1). The difference from two roundings is the point of the operation: for a=RN⁡(0.1)a = \operatorname{RN}(0.1) in binary64, the rounding error a⋅a−RN⁡(a⋅a)a \cdot a - \operatorname{RN}(a \cdot a) is lost by mul_ctx followed by sub_ctx (the second operation sees two equal numbers) but fma_ctx(a, a, -RN(a*a)) returns it exactly, −8.33…⋅10−19-8.33\ldots \cdot 10^{-19}. That the result is exact is Dekker’s theorem: the error of a rounded-to-nearest product is itself in FF when no underflow occurs (precisely, when ea+eb≥emin⁡−p+1e_a + e_b \ge e_{\min} - p + 1 for the exponents of the last bits of aa and bb, so the exact product lies on the grid of FF).55 T. J. Dekker, “A floating-point technique for extending the available precision”, Numerische Mathematik 18, 1971; Muller et al., §4.4. If the product exponent leaves the Int range, the product either certainly overflows, or it is so small that it acts as a sticky bit next to a nonzero addend; the code places a single bit p+9p + 9 positions below the addend’s last bit, which by the far-operand argument above rounds identically. With a zero addend such a product is the tiny result of the underflow rule.

IEEE remainder is exact

Claim. If x,y∈Fx, y \in F (same precision pp, same range) and y≠0y \ne 0, then r=x−nyr = x - n y with n=RNE⁡Z(x/y)n = \operatorname{RNE}_{\mathbb{Z}}(x/y) lies in FF.

Proof. Write x=Mx2qxx = M_x 2^{q_x}, y=My2qyy = M_y 2^{q_y} with ∣Mx∣,∣My∣<2p|M_x|, |M_y| < 2^p and qx,qy≥emin⁡−p+1q_x, q_y \ge e_{\min} - p + 1. By the choice of nn, ∣r∣≤∣y∣/2|r| \le |y|/2. If n=0n = 0 then r=xr = x. Otherwise ∣x/y∣≥12|x/y| \ge \frac12, so ∣r∣≤∣y∣/2≤∣x∣|r| \le |y|/2 \le |x|. Now rr is an integer multiple of 2min⁡(qx,qy)2^{\min(q_x, q_y)}.

  • If qx≥qyq_x \ge q_y: r=k2qyr = k 2^{q_y} with ∣k∣2qy≤∣My∣2qy/2|k| 2^{q_y} \le |M_y| 2^{q_y}/2, so ∣k∣<2p−1|k| < 2^{p-1}.
  • If qx<qyq_x < q_y: r=k2qxr = k 2^{q_x} with ∣k∣2qx≤∣x∣=∣Mx∣2qx|k| 2^{q_x} \le |x| = |M_x| 2^{q_x}, so ∣k∣<2p|k| < 2^{p}.

In both cases ∣k∣<2p|k| < 2^p, the exponent is at least emin⁡−p+1e_{\min} - p + 1, and ∣r∣≤max⁡(∣x∣,∣y∣)≤Ω|r| \le \max(|x|, |y|) \le \Omega, so r∈Fr \in F. □\square

The implementation never forms nn, which can have 2302^{30} bits. With X=∣x∣2−mX = |x| 2^{-m}, Y=∣y∣2−mY = |y| 2^{-m}, m=min⁡(qx,qy)m = \min(q_x, q_y) (integers), it computes X mod 2YX \bmod 2Y by modular exponentiation of 2qx−qy2^{q_x - q_y} when qx>qyq_x > q_y. Writing X=Q(2Y)+RX = Q (2Y) + R, 0≤R<2Y0 \le R < 2Y, gives ⌊X/Y⌋=2Q+[R≥Y]\lfloor X/Y \rfloor = 2Q + [R \ge Y], so RR alone yields both X mod YX \bmod Y and the parity of ⌊X/Y⌋\lfloor X/Y \rfloor, which is all the ties-to-even choice of nn needs. The exact rr then goes through the usual finalizer; by the claim, no rounding happens for operands of the context’s format.

Neighbours, scaling and integral values

next_up_ctx(x) adds a positive step 2π−22^{\pi - 2} to xx and rounds toward +∞+\infty, where π=min⁡(emin⁡−p, e(x), top⁡(x)−p)\pi = \min(e_{\min} - p,\ e(x),\ \operatorname{top}(x) - p). Every gap between consecutive points of FF next to xx is at least 2min⁡(emin⁡−p+1, top⁡(x)−p)2^{\min(e_{\min} - p + 1,\ \operatorname{top}(x) - p)} and xx itself is a multiple of 2e(x)2^{e(x)}, so x<x+2π−2<x+x < x + 2^{\pi - 2} < x^{+} for x∈Fx \in F, and by the definition of RU the result is the least point of FF above xx. The same argument works for an xx with more than pp bits, which is why such operands are accepted. The flags of this internal addition are discarded, because nextUp is quiet (clause 5.3.1) even when it steps from Ω\Omega to +∞+\infty.

scaleb_ctx(x, n) (with n an integer-valued Binary) is the finalizer applied to (c,e+n)(c, e + n): exact in the normal range, correctly rounded with underflow and overflow outside it. logb_ctx returns top⁡(x)\operatorname{top}(x), which is exact and correct for subnormal xx because top⁡\operatorname{top} is computed on the integer coefficient. The integral roundings use the same round and sticky bits with σ=−e\sigma = -e (the bits below the binary point); to_int_ctx and its siblings round first and then compare the integer with the target range, reporting invalid_operation instead of returning an implementation-defined sentinel.

Decimal conversion

Parsing. from_string_ctx reads D⋅10kD \cdot 10^{k} exactly (DD an integer without trailing zeros). For ∣k∣|k| up to max⁡(400,⌊(3n+p)/2⌋+64)\max\bigl(400, \lfloor (3n + p)/2 \rfloor + 64\bigr) (nn the number of digits) it is rounded exactly: D⋅5k⋅2kD \cdot 5^{k} \cdot 2^{k} by the dyadic finalizer for k≥0k \ge 0, and D/5∣k∣⋅2kD / 5^{|k|} \cdot 2^{k} by the division finalizer for k<0k < 0. Beyond that bound it uses directed enclosures [RD⁡w(D)RD⁡w(10k),RU⁡w(D)RU⁡w(10k)][\operatorname{RD}_w(D)\operatorname{RD}_w(10^k), \operatorname{RU}_w(D)\operatorname{RU}_w(10^k)] at a working precision ww, doubled until both ends round to the same value with the same flags. The bound makes the loop terminate. The rounding breakpoints of a direction are the points of FF (directed modes) or the midpoints between them (nearest modes); both are dyadic with at most p+1p + 1 significant bits. For k≥0k \ge 0 the odd part of D10kD 10^{k} is a multiple of 5k5^{k}, and 5k>22.32k>2p+25^{k} > 2^{2.32 k} > 2^{p+2} beyond the bound, so the value is no breakpoint: k>⌊(3n+p)/2⌋+64>(p+2)/2.32k > \lfloor (3n+p)/2 \rfloor + 64 > (p+2)/2.32. For k<0k < 0, ∣k∣>1.5n|k| > 1.5n gives 5∣k∣>10n>D5^{|k|} > 10^{n} > D, so 5∣k∣∤D5^{|k|} \nmid D and D/10∣k∣D/10^{|k|} is not even dyadic. The points where a flag changes (the overflow threshold, 2emin⁡2^{e_{\min}} for tininess, the points of FF for inexactness) are dyadic with at most p+1p + 1 significant bits as well. A value that is none of these has a positive distance to all of them, and the enclosure, whose relative width is O(2−w)O(2^{-w}), eventually lies strictly between two of them, so some ww certifies it; with no count limit (BinaryContext::with_refinement_limit(None)) the loop ends by itself once ww passes the work cap below. Values whose binary logarithm is certainly beyond the range, estimated with log⁡210\log_2 10 and a safety margin, overflow or underflow without any arithmetic, so 1e100000000 costs nothing.

Hexadecimal parsing. The value of a hexSequence is the integer of its hex digits times a power of two, so it is exactly a dyadic rational and no enclosure is needed: from_hex_ctx parses once (the grammar function is shared with from_hex) and hands the integer and the binary exponent to the same dyadic finalizer as the arithmetic operations, which applies the rounding direction, the exponent range, subnormals and the tininess rule, and returns the flags. A binary exponent beyond the 32-bit range is saturated: the value is then above 2231−12^{2^{31}-1} or below 2−231+b2^{-2^{31}+b} (bb the number of bits of the integer), outside every exponent range, so it overflows or underflows exactly as the saturated one does. from_hex keeps its own range check (a parse error beyond the 32-bit range) and its results for every in-range sequence.

Fixed digits. to_decimal_string_ctx(x, d) needs round⁡(x/10E−d+1)\operatorname{round}(x / 10^{E - d + 1}) with E=⌊log⁡10∣x∣⌋E = \lfloor \log_{10}|x| \rfloor. EE starts from ⌊top⁡(x)log⁡102⌋\lfloor \operatorname{top}(x) \log_{10} 2 \rfloor, which is within one of the answer, and is corrected by comparing ∣x∣|x| with 10E+110^{E+1}, first through directed bounds of the power and, when they straddle, exactly. The quotient is formed exactly as an integer division when its operands have at most 2202^{20} bits, so ties and exact results are recognised; otherwise directed enclosures are widened until both ends round to the same integer, which terminates because such a quotient is neither an integer nor a half-integer. A carry into a new leading digit (9.99→10.09.99 \to 10.0) increments EE and repeats.

Shortest output. Let I(x)I(x) be the set of reals that round to xx under RNE in the context; it is an interval containing xx. For each digit count nn, the two nn-digit decimals next to xx (truncated and rounded away from zero) are candidates, and a candidate is accepted when parsing it returns xx, that is when it lies in I(x)I(x). Acceptance is monotone in nn: if the nn-digit truncation dnd_n lies in I(x)I(x), the (n+1)(n+1)-digit truncation satisfies dn≤dn+1≤xd_n \le d_{n+1} \le x (in magnitude), so it lies in the interval too, and likewise for the upper neighbour. So the least accepted nn is found by bisection on [1,⌈plog⁡102⌉+2][1, \lceil p \log_{10} 2 \rceil + 2], an upper bound at which a candidate is always accepted.66 The digit count ⌈plog⁡102⌉+1\lceil p \log_{10} 2 \rceil + 1 suffices for round trip (Matula 1968; Goldberg 1991, Theorem 15); the extra digit is a margin for the bisection’s upper end. If both candidates are accepted, the nearer one is chosen, then the even one, which is the nearest decimal of that length. For binary64 this reproduces the host formatter on every value tested.

Certified elementary functions

Problem. For f=exp⁡,ln⁡,sin⁡,…f = \exp, \ln, \sin, \ldots the value f(x)f(x) is transcendental and must be rounded correctly without knowing it.

Options. Fixed polynomial approximations with a proven error bound (fast, but tied to one precision); Ziv’s strategy of evaluating with an a priori error bound and retrying at a higher precision when the rounding is ambiguous;77 A. Ziv, “Fast evaluation of elementary mathematical functions with correctly rounded last bit”, ACM TOMS 17(3), 1991; for interval evaluation see W. Tucker, Validated Numerics, Princeton 2011, and F. Johansson, “Arb: efficient arbitrary-precision midpoint-radius interval arithmetic”, IEEE Trans. Computers 66(8), 2017. or interval evaluation.

Choice. A Ziv loop whose error bound is not estimated but computed: every elementary function evaluates an enclosure [L,U]∋f(x)[L, U] \ni f(x) in which every internal operation is rounded downward for LL and upward for UU at a working precision ww. If

∘(L)=∘(U)andflags⁡(L)=flags⁡(U),\circ(L) = \circ(U) \quad\text{and}\quad \operatorname{flags}(L) = \operatorname{flags}(U),

the common value is returned, otherwise ww grows. The value is sound by (R2): L≤f(x)≤UL \le f(x) \le U implies ∘(L)≤∘(f(x))≤∘(U)\circ(L) \le \circ(f(x)) \le \circ(U), so equal ends force ∘(f(x))=∘(L)\circ(f(x)) = \circ(L).

The flags need a separate argument. Overflow and tininess (under either rule) depend only on ∣r∣|r| through a threshold, so on one side of zero they are monotone: if LL and UU (which have the same sign once they round to the same nonzero value) agree, every r∈[L,U]r \in [L, U] agrees with them. Inexactness is not monotone: it is false exactly on FF. If L<UL < U round to the same value vv with inexact, then f(x)f(x) is inexact unless f(x)=v∈Ff(x) = v \in F. The loop cannot tell these apart, so the flags are right only if every input whose exact result lies in FF is caught before the loop. That is why the exact cases below are filtered, and why an exact case that is missed shows up as a spurious inexact (nearest rounding) or as a budget failure (directed rounding, where LL and UU round to different neighbours of vv).

The enclosures come from series with rigorous tails and from monotone reductions. For exp⁡\exp on [0,1/8][0, 1/8], the terms tk=xk/k!t_k = x^k/k! satisfy tk+1/tk=x/(k+1)≤1/8t_{k+1}/t_k = x/(k+1) \le 1/8, so after the last summed term tnt_n

∑j>ntj≤tn∑i≥18−i=tn7≤2 tn,\sum_{j > n} t_j \le t_n \sum_{i \ge 1} 8^{-i} = \frac{t_n}{7} \le 2\, t_n,

and the code stops once tn<2−(w+8)t_n < 2^{-(w+8)} and adds 2tn2 t_n (rounded upward) to the upper sum; the lower sum of positive terms is already a lower bound. Larger arguments are halved rr times and the result squared rr times, which is monotone on positive numbers and therefore keeps the enclosure; e−x=1/exe^{-x} = 1/e^{x} handles negative arguments. For ln⁡v\ln v with v∈[1,2]v \in [1, 2] the series is

ln⁡v=2artanh⁡z=2∑k≥0z2k+12k+1,z=v−1v+1∈[0,13],\ln v = 2 \operatorname{artanh} z = 2 \sum_{k \ge 0} \frac{z^{2k+1}}{2k+1}, \qquad z = \frac{v - 1}{v + 1} \in \bigl[0, \tfrac13\bigr],

with tail ∑k≥mz2k+1/(2k+1)≤z2m+12m+1⋅11−z2\sum_{k \ge m} z^{2k+1}/(2k+1) \le \frac{z^{2m+1}}{2m+1} \cdot \frac{1}{1 - z^2}, the bound the code adds. The trigonometric functions reduce xx by an enclosure of π/2\pi/2 (the cached binary-splitting π\pi, see “Where π\pi comes from” below) at w≥p+max⁡(0,top⁡(x)+1)+96w \ge p + \max(0, \operatorname{top}(x) + 1) + 96 bits, so the quadrant k=round⁡(x/(π/2))k = \operatorname{round}(x / (\pi/2)) is the same integer at both ends of the enclosure; otherwise the attempt is repeated at a higher precision. This is the Payne–Hanek idea realised by brute precision instead of a stored table of 2/π2/\pi; its cost grows with log⁡2∣x∣\log_2|x|, so inputs needing more than 8,000,000 bits are refused with ResourceLimit rather than run for minutes.

Budget. The loop starts at w0=p+64w_0 = p + 64 (for some functions at the operand precision plus 16 when that is larger) and steps wi+1=wi+max⁡(32,⌊wi/2⌋)w_{i+1} = w_i + \max(32, \lfloor w_i/2 \rfloor), at most LL attempts, where LL is the refinement limit of the context (BinaryContext::refinement_limit, default 1212; a value below 11 counts as 11). For binary64 and L=12L = 12 the sequence is 117,175,262,…,10053117, 175, 262, \ldots, 10053 bits, and a hard-to-round input that needs more than that fails with a CertificationFailure carrying the refinement count; Some(n) with a larger nn certifies it.

With LL = None the count is unbounded, but the loop is not: it stops, with the same CertificationFailure, when ww exceeds max⁡(8 000 000, 256 w0)\max(8\,000\,000,\ 256\,w_0) bits (capped at 10910^9 so ww fits Int32), and a trigonometric argument that needs more than 8 000 0008\,000\,000 bits for its reduction is still refused with ResourceLimit whatever the limit. So None cannot allocate without bound: each step costs O(M(w))O(M(w)) for the working precision w≤w \le the cap, and the number of steps is at most log⁡1.5(cap/w0)\log_{1.5}(\text{cap}/w_0). A result that sits at distance δ\delta from a breakpoint needs w≈log⁡2(1/δ)w \approx \log_2(1/\delta), so the default L=12L = 12 decides everything farther than about 2−100002^{-10000} from a breakpoint at binary64 and None extends that to the cap. Functions without a context argument (the Interval enclosures) keep 1212. The exact fallback of the integer power pown (12 Ziv rounds, then an exact product) cannot fail and is not governed by the limit.

Termination. Ziv’s argument has two parts. First, f(x)f(x) must not be a breakpoint of ∘\circ (a point of FF, a midpoint, or a flag threshold), all of which are dyadic. For a nonzero dyadic xx, exe^{x}, sin⁡x\sin x, cos⁡x\cos x, tan⁡x\tan x, the hyperbolic functions, their inverses and ln⁡x\ln x (x≠1x \ne 1) are transcendental by Lindemann–Weierstrass. For 2x2^x, 10x10^x, log⁡2x\log_2 x and log⁡10x\log_{10} x irrationality is enough and elementary: 2a/b2^{a/b} with b∤ab \nmid a is irrational, so 2x2^x is dyadic only for integral xx, and log⁡2x=a/b\log_2 x = a/b forces x=2a/bx = 2^{a/b}, a power of two; likewise 10x10^x and log⁡10x\log_{10} x are dyadic only at integral x≥0x \ge 0 and at x=10kx = 10^k. For the π\pi-scaled functions Niven’s theorem shows that integral, half-integral and (for tanpi) quarter-integral arguments are the only dyadic exceptions.88 I. Niven, Irrational Numbers, 1956, Corollary 3.12: if rr is rational and sin⁡(πr)\sin(\pi r) is rational, then sin⁡(πr)∈{0,±12,±1}\sin(\pi r) \in \{0, \pm\frac12, \pm 1\}; similarly for cos⁡\cos, and tan⁡(πr)∈{0,±1}\tan(\pi r) \in \{0, \pm 1\}. The value ±12\pm\frac12 needs rr with denominator 6 or 3, which is not dyadic. For pow and rootn the exceptions are characterised under Exact powers and roots below. The exceptions are filtered before the loop: e0=1e^0 = 1, ln⁡1=0\ln 1 = 0, log⁡22k=k\log_2 2^k = k, 2n2^n for integral ∣n∣<231|n| < 2^{31}, sin⁡(±0)\sin(\pm 0), the π\pi-scaled cases, 10n10^n for integral 0≤n≤max⁡(4096,p)0 \le n \le \max(4096, p) (beyond that the odd part 5n5^n has more than p+1p + 1 bits, so 10n10^n is not a breakpoint), log⁡1010n\log_{10} 10^n for every n≥1n \ge 1, dyadic powers and exact roots, and so on.

Second, the enclosure must shrink onto f(x)f(x) fast enough. The series stop when the next term is below 2−(w+8)2^{-(w+8)} or 2−(w+12)2^{-(w+12)} in absolute value, which is fine for arguments of moderate size; the width then is O(2−w)O(2^{-w}) relative to f(x)f(x), a non-breakpoint has a positive distance to every breakpoint, and some ww certifies it. Tiny arguments need the two measures under Tiny arguments below. How large ww must be is the table maker’s dilemma: no useful a priori bound is known for arbitrary pp, so the budget is a resource limit, not a correctness condition. When it runs out the try_* form reports a CertificationFailure with the stage, the reason and the last ww, and the total forms return a quiet NaN with invalid_operation; neither returns an uncertified value. The pinned MPFR corpus never exhausts it.

Exact powers and roots. An integral exponent with ∣y∣<231|y| < 2^{31} goes to pown. A larger integral yy needs no filter: for x=c⋅2ex = c \cdot 2^e with c>1c > 1 odd, c∣y∣c^{|y|} has more than 231>p+12^{31} > p + 1 bits, and a power of two 2ey2^{ey} lies outside every exponent range, so neither is a breakpoint. Every other exponent is y=m/2ky = m / 2^k with mm odd and k≥1k \ge 1. If xyx^y is rational, so is q=x∣y∣q = x^{|y|}, and x∣m∣=q2kx^{|m|} = q^{2^k}; comparing the exponents of 22 and of each odd prime gives q=a⋅2fq = a \cdot 2^f with aa odd, e∣m∣=f⋅2ke|m| = f \cdot 2^k and c∣m∣=a2kc^{|m|} = a^{2^k}. Since ∣m∣|m| is odd, 2k∣e2^k \mid e and every prime exponent of cc is divisible by 2k2^k, so c=r2kc = r^{2^k} and q=r∣m∣⋅2e∣m∣/2kq = r^{|m|} \cdot 2^{e|m|/2^k}. Conversely these values are exact. So a rational pow result exists exactly under these two divisibility conditions; for m>0m > 0 it is the dyadic qq, and for m<0m < 0 it is 1/q1/q, which is dyadic only when r=1r = 1. Every other pow result is irrational. binary_pow_exact_dyadic computes the dyadic results and rounds them once, unless the odd part rmr^m would need more than 2p+642p + 64 bits (then it has more than p+1p + 1 significant bits and is not a breakpoint). The same argument with 1/∣n∣1/|n| in place of ∣y∣|y| shows that rootn⁡(x,n)\operatorname{rootn}(x, n) is rational exactly when ∣n∣∣e|n| \mid e and c=r∣n∣c = r^{|n|}; rootn returns ±r⋅2e/∣n∣\pm r \cdot 2^{e/|n|} rounded once for n>0n > 0, and for n<0n < 0 the correctly rounded quotient 1/(±r⋅2e/∣n∣)1 / (\pm r \cdot 2^{e/|n|}), which division decides with the right inexact flag although it need not be dyadic. The perfect-power test has no size limit. It first takes square roots with remainder for every factor 22 of the degree, stopping at the first nonzero remainder, and then the floor of the remaining odd root: by bisection while the root has at most 64 bits, otherwise by integer Newton steps r←⌊((d−1)r+⌊c/rd−1⌋)/d⌋r \leftarrow \lfloor ((d-1) r + \lfloor c / r^{d-1} \rfloor) / d \rfloor started just above the root, which decrease monotonically to ⌊c1/d⌋\lfloor c^{1/d} \rfloor; one power rdr^d then decides exactness. A coefficient with at most dd bits other than 11 is rejected at once, because r≥2r \ge 2 gives rd≥2dr^d \ge 2^d.

A negative base with an integral exponent beyond the pown range is evaluated as ±∣x∣y\pm|x|^y. Negation is an exact symmetry of ∘\circ that swaps the two directed modes, ∘RD(−v)=−∘RU(v)\circ_{\mathrm{RD}}(-v) = -\circ_{\mathrm{RU}}(v), so for an odd yy the code rounds ∣x∣y|x|^y with RD and RU exchanged and negates.

Tiny arguments. For small enough ∣x∣|x| (about 2−p/22^{-p/2} for the odd functions, 2−p2^{-p} for exe^x) the result lies closer to a representable number aa than the target spacing: a=xa = x for the odd functions, a=1a = 1 for exe^x, cos⁡\cos, cosh⁡\cosh. An enclosure whose series stops after its first term then has aa itself as one end (U=xU = x for sin⁡\sin, L=1L = 1 for exe^x), and that end rounds without inexact while the other end rounds with it, so the acceptance test alone would only pass once ww separates f(x)f(x) from aa, at w≈log⁡2(1/∣x∣)w \approx \log_2(1/|x|) or more. Two measures remove the dependence on ∣x∣|x|.

Inner endpoints. Every result that reaches the loop is known not to be a breakpoint. For every function other than pow and rootn, binary_certified_inexact_target_rounding replaces an end EE that could be a breakpoint (an odd coefficient of at most p+1p + 1 bits) by E′=E±2eE−sE' = E \pm 2^{e_E - s} toward the inside of the enclosure, with s=max⁡(1,p+3−bits⁡(cE))s = \max(1, p + 3 - \operatorname{bits}(c_E)). If the leading bit of EE is 2t2^t, breakpoints near EE are at least 2t−p−12^{t - p - 1} apart and the offset is at most 2t−p−22^{t - p - 2}, so no breakpoint lies in (E,E′](E, E']. Since f(x)≠Ef(x) \ne E, either f(x)f(x) lies beyond E′E' or between EE and E′E', and in the second case it shares the open cell between breakpoints with E′E' and rounds like it. So ∘(E′)=∘(U′)\circ(E') = \circ(U') with equal flags still forces ∘(f(x))\circ(f(x)) and its flags, and the test passes as soon as the enclosure is narrower than the spacing, independently of ∣x∣|x|. pow uses inner endpoints whenever its exactness test (above) has shown that the result is irrational, not dyadic, or wider than p+1p + 1 bits, so a tiny exponent with xyx^y closer to 11 than the target spacing is certified too (22−160002^{2^{-16000}} in binary128 is 11 with inexact). The test leaves a few cases with a power-of-two base undecided (an exponent of magnitude at least 2312^{31}, or a scale outside the 32-bit range); those keep the plain acceptance test.

Tiny-argument bounds. Some enclosures (for sinh⁡\sinh, tanh⁡\tanh via ex−e−xe^x - e^{-x}, and for asinh⁡\operatorname{asinh}, atanh⁡\operatorname{atanh}, asin⁡\operatorname{asin}, tan⁡\tan, expm1, log1p) straddle the neighbour of aa until w≈3log⁡2(1/∣x∣)w \approx 3\log_2(1/|x|). For ∣x∣≤1/2|x| \le 1/2 the series give one-sided bounds with a known side: 0<x−sin⁡x0 < x - \sin x, 0<tan⁡x−x0 < \tan x - x, 0<asin⁡x−x0 < \operatorname{asin} x - x, 0<sinh⁡x−x0 < \sinh x - x, 0<x−tanh⁡x0 < x - \tanh x, 0<x−asinh⁡x0 < x - \operatorname{asinh} x, 0<atanh⁡x−x0 < \operatorname{atanh} x - x, each at most ∣x∣3|x|^3 (for x>0x > 0, mirrored for x<0x < 0), and 0<1−cos⁡x0 < 1 - \cos x, 0<cosh⁡x−10 < \cosh x - 1, 0<expm1⁡(x)−x0 < \operatorname{expm1}(x) - x, 0<x−log1p⁡(x)0 < x - \operatorname{log1p}(x), each at most x2x^2. With ∣x∣<2T|x| < 2^T, binary_tiny_argument_result uses the enclosure [a,a+2σ][a, a + 2^{\sigma}] or [a−2σ,a][a - 2^{\sigma}, a] with σ=3T\sigma = 3T (respectively 2T2T), raised to at least ta−p−8t_a - p - 8, when σ<ta−p−3\sigma < t_a - p - 3 (2ta2^{t_a} the leading bit of aa), and rounds it with inner endpoints. The condition implies ∣x∣<2−(p+3)/2≤1/2|x| < 2^{-(p+3)/2} \le 1/2, so the bounds apply, and the enclosure is at most a quarter of the breakpoint spacing at aa wide. When aa is a breakpoint, both ends lie in the cell next to aa and the result is decided before the loop; otherwise (an argument wider than p+1p + 1 bits) the loop runs as usual. With both measures sin and atan of 2−60002^{-6000} at 53 bits and e2−20000e^{2^{-20000}} are certified in every rounding mode.

rootn keeps the plain test, and pow uses it only for the few results its exactness test cannot classify. For rootn it suffices: its enclosure is eln⁡(x)/ne^{\ln(x)/n} at a working precision above the operand precision qq, and ∣ln⁡x∣/∣n∣>2−(q+31)|\ln x| / |n| > 2^{-(q + 31)} for x≠1x \ne 1 and ∣n∣≤109|n| \le 10^9, so an end at 11 disappears after an attempt or two. pow evaluates eyln⁡xe^{y \ln x}, where yy can be arbitrarily small: an exponent so small that xyx^y lies closer to 11 than the target spacing gives an enclosure with L=1L = 1 at every affordable ww. That is why pow moves such an end inward once its exactness test has excluded a breakpoint, as described under inner endpoints; for example 22−160002^{2^{-16000}} in binary128 is then 11 with inexact.

Integer powers. pown_ctx computes xnx^n by an addition chain at w=p+bits⁡(n)+bits⁡(p)+4w = p + \operatorname{bits}(n) + \operatorname{bits}(p) + 4 bits with round-to-nearest. Each chain step ak=ai+aja_k = a_i + a_j multiplies two approximations; if xa∏(1+δ)E(a)x^{a} \prod (1 + \delta)^{E(a)} describes the error structure, then E(ak)=E(ai)+E(aj)+1E(a_k) = E(a_i) + E(a_j) + 1 and E(1)=0E(1) = 0, so by induction E(a)≤a−1E(a) \le a - 1. The computed value is therefore xn(1+θ)x^n (1 + \theta) with ∣θ∣≤γn−1=(n−1)uw/(1−(n−1)uw)|\theta| \le \gamma_{n-1} = (n-1)u_w/(1 - (n-1)u_w) in Higham’s notation, which is below 2bits⁡(n)2^{\operatorname{bits}(n)} units in the last place of the ww-bit result. The code uses the radius 2bits⁡(n)+22^{\operatorname{bits}(n) + 2} units (one more factor of two for a negative power, whose reciprocal adds nn further factors), builds the interval, and accepts when both ends round alike, by the same (R2) argument. When 12 attempts (with ww doubled between them) do not certify, the exact power cn2nec^n 2^{ne} is formed and rounded, so the result is correctly rounded in every case. A power certainly outside the range is decided first from certified log⁡2\log_2 bounds; powers of two and powers whose exact value fits in pp bits are computed exactly. The Ziv path therefore only sees cnc^n with c>1c > 1 odd and more than pp bits, or 1/cn1/c^n, which is not dyadic: neither is in FF, so the inexact it reports is right (the flag argument above). A cnc^n with exactly p+1p + 1 bits is a midpoint; the enclosure then never certifies under nearest rounding and the exact fallback decides it.

hypot. hypot forms a2+b2a^2 + b^2 exactly from the coefficients and takes one correctly rounded square root, so it needs no loop; the cost is the alignment shift between the two squares. For ∣a∣≥∣b∣>0|a| \ge |b| > 0, ∣a∣<a2+b2≤∣a∣+b2/(2∣a∣)|a| < \sqrt{a^2 + b^2} \le |a| + b^2 / (2|a|). Write ∣a∣=c⋅2e|a| = c \cdot 2^e with leading bit 2t2^t and g=2min⁡(e, t−p−1)g = 2^{\min(e,\, t - p - 1)}: ∣a∣|a| and every rounding breakpoint near it are multiples of gg, so when b2<2∣a∣gb^2 < 2|a|g no breakpoint lies in (∣a∣,∣a∣+b2/(2∣a∣)](|a|, |a| + b^2/(2|a|)] and every such bb gives the same rounded result and flags. ∣b∣<g/8|b| < g/8 is enough, and binary_hypot_negligible_operand then replaces bb by g/8g/8, which keeps the shift at about twice the operand and target precisions however far apart the exponents are (hypot⁡(1,2−600000)=1\operatorname{hypot}(1, 2^{-600000}) = 1 with inexact). A shift above 10610^6 bits is still refused as a certification_failure; after the replacement it needs a precision near 500 000500\,000 bits.

atan, asin, acos and atan2: one evaluation chain for the pair. The enclosure of atan⁡\operatorname{atan} over a pair [a,b][a, b] is computed by one chain, not by one chain per endpoint. atan⁡\operatorname{atan} is odd and increasing, so L=lower⁡(atan⁡ a)L = \operatorname{lower}(\operatorname{atan}\,a) and U=upper⁡(atan⁡ b)U = \operatorname{upper}(\operatorname{atan}\,b) enclose atan⁡\operatorname{atan} on the whole pair. For 0≤a≤b0 \le a \le b and b>1/2b > 1/2 the reduction is atan⁡ x=2atan⁡ r(x)\operatorname{atan}\,x = 2 \operatorname{atan}\, r(x) with r(x)=x/(1+1+x2)=tan⁡(atan⁡(x)/2)r(x) = x / (1 + \sqrt{1 + x^2}) = \tan(\operatorname{atan}(x)/2), which is increasing on x≥0x \ge 0 (it is a composition of increasing maps). Hence [r−(a),r+(b)]∋r(x)[r^-(a), r^+(b)] \ni r(x) for every x∈[a,b]x \in [a, b], where r−(a)r^-(a) divides aa rounded down by an upper bound of 1+1+a21 + \sqrt{1 + a^2} and r+(b)r^+(b) divides bb rounded up by a lower bound of 1+1+b21 + \sqrt{1 + b^2}; the bounds of the denominator are directed squares, sums and square roots, each monotone on nonnegative numbers. The reduced pair is again nonnegative and ordered, so the recursion is a chain (two levels at most, because r(x)<1r(x) < 1 and r(1)<1/2r(1) < 1/2), and the Taylor series runs once, with its lower track on the lower end and its upper track on the upper end. A negative pair [a,b][a, b] is −[−b,−a]-[-b, -a]; a pair that contains zero is widened to [−m,m][-m, m] with m=max⁡(−a,b)m = \max(-a, b), which contains it. The old code evaluated the series once for ∣x∣≤1/2|x| \le 1/2, twice up to 4/34/3 and four times above (a lower and an upper call per reduction level); a point argument now costs one series at every size.

Large arguments. The square x2x^2 of the reduction leaves the exponent range for ∣x∣≥2229|x| \ge 2^{2^{29}}, so for a leading bit of xx of at least 2w+22w + 2 the reduction is formed without it: with y=1/xy = 1/x, r(x)=1/(y+1+y2)r(x) = 1 / (y + \sqrt{1 + y^2}) and 1+y≤y+1+y2≤1+y+y21 + y \le y + \sqrt{1 + y^2} \le 1 + y + y^2, hence 1/(1+y+y2)≤r(x)≤1/(1+y)1/(1 + y + y^2) \le r(x) \le 1/(1 + y), evaluated with directed reciprocals of xx; the relative gap is below 2y≤2−2w−12y \le 2^{-2w-1}. An infinite end of a pair (a quotient of atan2 that overflowed) is bounded by π/2\pi/2 rounded in the matching direction. The test atan_single_evaluation_wbtest.mbt covers 3⋅2e3 \cdot 2^e for ee on both sides of 2292^{29} and near 2302^{30}, both signs and three rounding directions, against π/2\pi/2 from the cached constant; the public results equal those of the previous code there.

For asin⁡\operatorname{asin} the pair is the ratio f(x)=x/1−x2f(x) = x / \sqrt{1 - x^2}, increasing on (−1,1)(-1, 1). With 1−x2∈[ρ−,ρ+]\sqrt{1 - x^2} \in [\rho^-, \rho^+] on the operand pair (directed roots of directed 1−x21 - x^2), the lower end is a/ρ−a / \rho^- if a<0a < 0 and a/ρ+a / \rho^+ if a≥0a \ge 0, the upper end is b/ρ−b / \rho^- if b≥0b \ge 0 and b/ρ+b / \rho^+ if b<0b < 0, which replaces the eight directed quotients and the search for their minimum and maximum. For atan2⁡\operatorname{atan2} and atan2Pi⁡\operatorname{atan2Pi} the ratio y/xy / x of a rectangle with xx of one strict sign takes its extremes at the corners selected by the signs of the ends of yy (four directed divisions replace the eight of the previous search). The soundness of the new evaluation is tested against the previous functions, kept as test-only copies, evaluated at 128 more bits (atan_single_evaluation_wbtest.mbt); the Ziv loops take the same number of attempts on that corpus. A pair that is wide because the operand is (asin close to 11) can come out up to about 1.4 times wider than before, because the alternating-series bracket pairs the lower track with the terms of the other end; narrow pairs differ by a few units in the last place.

The arctangent leaf in fixed point. On [0,12][0, \tfrac12] the series is evaluated as arctan⁡x=x−R(x)\arctan x = x - R(x) with R(x)=x3/3−x5/5+x7/7−⋯R(x) = x^3/3 - x^5/5 + x^7/7 - \cdots, increasing in xx, so on a pair [a,b][a, b] the enclosure is [ a−R+, b−R− ][\,a - R^{+},\ b - R^{-}\,] with R−≤R(a)R^{-} \le R(a) and R(b)≤R+R(b) \le R^{+}. RR is computed with integers of F=w+q+20+bits⁡(w)F = w + q + 20 + \operatorname{bits}(w) fractional bits, where q=−top⁡(b)q = -\operatorname{top}(b): a lower chain Pk−≤a2k+12FP^{-}_k \le a^{2k+1} 2^F by floors and an upper chain Pk+≥b2k+12FP^{+}_k \ge b^{2k+1} 2^F by ceilings (each step multiplies by a floor or ceiling of the square and shifts, and a floor of a product of lower bounds, or a ceiling of a product of upper bounds, keeps the bound), then Tk−=⌊Pk−/(2k+1)⌋T^{-}_k = \lfloor P^{-}_k / (2k+1) \rfloor and Tk+=⌈Pk+/(2k+1)⌉T^{+}_k = \lceil P^{+}_k / (2k+1) \rceil by a division by a single word. For terms decreasing in size the partial sum after an odd number of terms is at least RR and after an even number at most RR; with A=∑k oddTk+A = \sum_{k \text{ odd}} T^{+}_k, B=∑k evenTk−B = \sum_{k \text{ even}} T^{-}_k, C=∑k oddTk−C = \sum_{k \text{ odd}} T^{-}_k and D=∑k evenTk+D = \sum_{k \text{ even}} T^{+}_k this gives R+=A−BR^{+} = A - B (odd partial sum, upper terms added, lower terms subtracted) and R−=C′−DR^{-} = C' - D (even partial sum, C′C' without the last odd term), and the loop stops at an odd kk whose Tk+T^{+}_k is below two units. Every floor or ceiling loses at most one unit and x2≤14x^2 \le \tfrac14, so the chain errors stay below two units, each term is within three, and the whole enclosure within 1.5F1.5 F units of 2−F2^{-F}, which the 20 and bits⁡(w)\operatorname{bits}(w) guard bits cover relative to x≥2−qx \ge 2^{-q}. For q≥w/2+8q \ge w/2 + 8 the series is not run: 0≤R(x)≤x3/30 \le R(x) \le x^3/3 and x3/3<x 2−w−14x^3/3 < x\, 2^{-w-14}, so the enclosure is [ a−b3/3, b ][\,a - b^3/3,\ b\,]. Where the previous floating-point leaf ran four rounded Binary operations per term, a term is now two integer products and two single-word divisions: instructions retired for atan, asin, acos and atan2 fall by 2.1 to 2.5 times at 53, 128 and 512 bits. The tests keep the floating-point leaf as a copy and check that the new enclosure contains the old one at 128 more bits (points, neighbouring and wide pairs, a pair starting at zero) and at both sides of the threshold q=w/2+8q = w/2 + 8.

Where π\pi comes from. The binary-splitting π\pi of this package is cached per working precision. Binary +∞+\infty .try_atan_ctx returns the correctly rounded π/2\pi/2 from that cache, so decimal and interval obtain [RD⁡(π),RU⁡(π)][\operatorname{RD}(\pi), \operatorname{RU}(\pi)] from two calls (rounding downward and upward) and a scaling by 22, which is exact: the same interval, bit for bit, as 4 [RD⁡(atan⁡1),RU⁡(atan⁡1)]4\,[\operatorname{RD}(\operatorname{atan} 1), \operatorname{RU}(\operatorname{atan} 1)], since scaling by a power of two commutes with directed rounding. No public function was added for it.

sinh, cosh and tanh from one exp. With [L,U]∋ex[L, U] \ni e^{x} from one kernel call and 0<L0 < L, the enclosure of e−xe^{-x} is [1/U,1/L][1/U, 1/L] with directed divisions (the reciprocal is decreasing); if LL is not positive (an underflowed enclosure) the kernel is called on −x-x as before. sinh⁡\sinh and cosh⁡\cosh then combine the four ends as before. For tanh⁡=s/c\tanh = s / c with 0<c0≤c≤c10 < c_0 \le c \le c_1 and s∈[s0,s1]s \in [s_0, s_1] the quotient is increasing in ss and, for s≥0s \ge 0, decreasing in cc (the reverse for s<0s < 0), so the extremes are s0/c1s_0 / c_1 if s0≥0s_0 \ge 0 and s0/c0s_0 / c_0 otherwise (lower end), s1/c0s_1 / c_0 if s1≥0s_1 \ge 0 and s1/c1s_1 / c_1 otherwise (upper end): two divisions instead of eight. At arguments where e∣x∣e^{|x|} leaves the exponent range the enclosures are the same as before (sinh⁡\sinh, cosh⁡\cosh) or [0,∞][0, \infty] instead of a NaN end (tanh⁡\tanh), and the public results did not change in the tests at those arguments.

Corners by sign. The product of two intervals [a0,a1]⋅[b0,b1][a_0, a_1] \cdot [b_0, b_1] is no longer the minimum and maximum of four rounded products. With aa nonnegative, the smallest aba b over the box is a0b0a_0 b_0 if b0≥0b_0 \ge 0 and a1b0a_1 b_0 otherwise (take the smallest bb, then the aa that suits its sign), and the largest is a1b1a_1 b_1 if b1≥0b_1 \ge 0 and a0b1a_0 b_1 otherwise; a nonpositive aa is −∣a∣-|a| and a mixed aa with a sign-definite bb swaps the roles; two mixed intervals still take the four corners. The quotient by a positive interval [d0,d1][d_0, d_1] has the lower end n0/d1n_0 / d_1 if n0≥0n_0 \ge 0 and n0/d0n_0 / d_0 otherwise, and the upper end n1/d0n_1 / d_0 if n1≥0n_1 \ge 0 and n1/d1n_1 / d_1 otherwise. Directed rounding is monotone, so the rounded exact extreme equals the extreme of the rounded corners. One thing is not monotone: the sign of a zero end depends on which of several equal candidates the old code kept, so when an end is zero the old four-candidate form is used and the results stay bit-identical.

Trigonometric functions: no reduction near zero, one series for a point. If both ends of the argument enclosure lie strictly inside (−π/4,π/4)(-\pi/4, \pi/4) (the lower bound of π/4\pi/4 is half the lower bound of π/2\pi/2, exact), then x/(π/2)∈(−12,12)x / (\pi/2) \in (-\tfrac12, \tfrac12) at both ends, the nearest integer is 00 for both, the product 0⋅π/20 \cdot \pi/2 is 00 and the reduced argument is the input itself; the division by π/2\pi/2 and the multiplication back are skipped, and the result is the one of the general path. When the reduced pair is a point (equal ends) the series is evaluated once and its two ends are used for both bounds, as evaluating twice gives the same value; tan takes the quotient corner by the sign of the cosine enclosure (a negative cosine uses n/d=(−n)/(−d)n / d = (-n) / (-d)). The same point shortcut is used in exp2, exp10, pow, rootn, log1p, asinh, acosh, atanh, expm1-based exp2m1 and exp10m1, and compound: binary_bounds_at_ends takes the lower end of the evaluation at the lower argument and the upper end of the evaluation at the upper argument, and evaluates once when the two arguments are equal.

Trigonometric functions: one series at the midpoint of a reduced interval. When the argument needs the reduction, the reduced enclosure [ℓ,u][\ell, u] of x−nπ/2x - n \pi/2 has two distinct ends (it comes from both bounds of π\pi), and the enclosure of the series used to be the lower end of the series at ℓ\ell and the upper end of the series at uu: two series evaluations. Sine and cosine are 1-Lipschitz (∣sin⁡′∣=∣cos⁡∣≤1|\sin'| = |\cos| \le 1, ∣cos⁡′∣=∣sin⁡∣≤1|\cos'| = |\sin| \le 1). Take any value mm (here the midpoint (ℓ+u)/2(\ell + u)/2 rounded to nearest at the working precision) and h=max⁡(u−m, m−ℓ)h = \max(u - m,\ m - \ell) with both differences rounded upward; then every x∈[ℓ,u]x \in [\ell, u] has ∣x−m∣≤h|x - m| \le h, so ∣f(x)−f(m)∣≤h|f(x) - f(m)| \le h and f(x)∈[f(m)low−h, f(m)high+h]f(x) \in [f(m)_{\mathrm{low}} - h,\ f(m)_{\mathrm{high}} + h] with the two sums rounded outward, where [f(m)low,f(m)high][f(m)_{\mathrm{low}}, f(m)_{\mathrm{high}}] is the series enclosure at mm. Soundness does not need mm to lie in [ℓ,u][\ell, u], since hh covers both distances whatever mm is. The widened enclosure is then clamped to what is known of the function: the range bounds −1-1 and 11 for both functions (and the cosine keeps its upper end 11 when 0∈[ℓ,u]0 \in [\ell, u]), and, for a sine whose reduced interval has ends of one sign, the sign (the lower end is at least 00 when ℓ>0\ell > 0, the upper end at most 00 when u<0u < 0). The clamp matters by this rule: a widened end that crosses a bound the true value sits on, or within the directed-rounding unit of at every work precision, never converges, while one that crosses a bound the true value is strictly inside of converges as refinement shrinks hh. The cosine of a tiny argument is 1−x2/21 - x^2/2, closer to 11 than the work precision resolves, so the unclamped upper end 1+h1 + h lies above the breakpoint 11 for ever and a directed rounding never reaches one value (the first form of this change returned an error, a NaN from cospi, for such arguments). No other result is of that kind: the sine of a point interval is not widened (its upper end is the series’ own), and for the distinct ends of sinpi and tanpi of a tiny argument the widened upper end exceeds the two-ended one by at most one unit of the work precision, which is the strictly inside kind. No two-ended fallback remains. The endpoint 11 is then decided by binary_inexact_inner_endpoint, inside binary_certified_inexact_target_rounding (the step of every refinement loop of these functions): the result is known not to be representable, so an enclosure end that is a rounding breakpoint of the target format is moved strictly inside, and [1−d,1][1 - d, 1] certifies a directed rounding; the end 1+h1 + h of the first form has far more bits than a breakpoint, so that step did not apply to it. The same holds for −1-1, which only the quadrant maps produce (as the negation of the capped cosine upper end). Near the bottom of the exponent range the ends and hh are rounded to the quantum of the work precision (a value of width ww stores nothing below 2emin⁡−(w−1)2^{e_{\min} - (w - 1)}); while at least 64 bits of the product lie above the quantum, hh is a few quanta against a midpoint of many bits and the lower end of the sine stays positive, and where fewer remain (the smallest subnormal of a wide precision used at a narrow one) the widened lower end can reach 00 or below and is clamped at 00, as the two-ended lower end was at most the quantum. One series is evaluated instead of two, the half-width enters the radius as an upper bound, and nothing else changes: tan takes the quotient of the two enclosures as before, so it needs no derivative bound of its own, and the widened cosine enclosure still excludes 00 wherever the two-ended one did (the reduced argument is within π/4\pi/4, so the cosine is at least 0.70710.7071 and hh is a few units of the working precision). The new enclosure contains the exact value and is at most u−ℓu - \ell wider on each side than the two-ended one (where the derivative is small the two-ended enclosure was narrower than the interval); u−ℓu - \ell is a few units of the working precision (for a huge argument the ends are first rounded outward to the series precision, so it is of the order of the series error already in the enclosure), so the uniqueness test of the final rounding and the refinement loop are unchanged and can only retry when the result lies within u−ℓu - \ell of a rounding boundary. The tests keep the two-ended function and check that the new enclosure lies inside the old one widened by 2(u−ℓ)2 (u - \ell) plus a few units, that both contain the enclosure at a working precision 256 bits higher, that tan declines exactly where the old one does, and a named test of an argument with an exponent of a few thousand. A sweep of sin, cos, tan, sinpi, cospi and tanpi of ±2e\pm 2^e and ±3⋅2e\pm 3 \cdot 2^e for ee from −60-60 down to the bottom of the range, of the smallest subnormals of each tested precision and the quanta above them, and of floats just above, at and below multiples of π/2\pi/2, in the five rounding directions at precisions 22, 33, 2424, 5353 and 113113, pins every value and flag to the two-ended form, requires no NaN, and fails if a case takes more refinement rounds than the two-ended form plus one. Why the first form passed its tests: the random operands (1.26 million) and the huge-argument test never ran a directed rounding on a result within one unit of the range bound, so the enclosure above 11 never mattered; a reviewer of a change that widens an enclosure should ask for the directed-mode sweep at the range bounds first.

rootn and rsqrt by one integer root. For 2≤∣n∣≤322 \le |n| \le 32 (within the gate described below) the result is rounded in one step, without a Ziv loop. For a positive x=c2ex = c 2^{e} with 2t≤x<2t+12^t \le x < 2^{t+1}, the top bit of x1/nx^{1/n} is k=⌊t/n⌋k = \lfloor t/n \rfloor (t+1≤n(k+1)t + 1 \le n (k + 1) because t<n(k+1)t < n (k + 1) are integers); the top bit of x−1/nx^{-1/n} is −k−1-k - 1, or −⌈t/n⌉-\lceil t/n \rceil when c=1c = 1 (x=2tx = 2^t exactly), by the same inequality on 1/x1/x. With TT the exponent of the last place of the rounded result (the subnormal grid included), take g=T−1g = T - 1 (half a unit) and the integer y=⌊x2−ng⌋y = \lfloor x 2^{-n g} \rfloor (for x1/nx^{1/n}) or ⌊2−ng/x⌋\lfloor 2^{-n g} / x \rfloor (for x−1/nx^{-1/n}); since ⌊v1/n⌋=⌊⌊v⌋1/n⌋\lfloor v^{1/n} \rfloor = \lfloor \lfloor v \rfloor^{1/n} \rfloor for real v≥0v \ge 0 (an integer rr has rn≤vr^n \le v exactly when rn≤⌊v⌋r^n \le \lfloor v \rfloor), r2=⌊y1/n⌋r_2 = \lfloor y^{1/n} \rfloor (the integer square root kernel for n=2n = 2, the integer Newton root otherwise) is ⌊∣x∣±1/n/2g⌋\lfloor |x|^{\pm 1/n} / 2^{g} \rfloor. The retained part is r2≫1r_2 \gg 1, the round bit is the low bit of r2r_2, and the sticky bit is “the root is not exactly r22gr_2 2^{g}”, which holds unless yy was exact (no dropped bits, no remainder) and y=r2ny = r_2^n: a boundary of any rounding direction is a multiple of half a unit, so a root strictly between r2r_2 and r2+1r_2 + 1 is on the same side of every boundary as r2r_2 with the sticky bit set. binary_round_pack then decides the result and the flags as for the square root, including the subnormal range and the tininess rule after rounding (a second root on the unbounded grid when it differs). The integer has about n(p+2)n (p + 2) bits and the Newton steps of its root raise a number of that size to the power n−1n - 1, so the path is used only where it is measurably faster than the certified exp(ln(x) / n) loop, which gets the fast exp and ln kernels from about 1500 bits on. Instructions retired, loop divided by integer root: for n≤12n \le 12 the integer root wins at every precision measured (53 to 32768 bits) by 2.4 to 300 times; for 13≤n≤3213 \le n \le 32 it wins by 6.7 to 49 times up to 1024 bits, but at 2048 bits n=16n = 16 gains only 1.6 times, n=20n = 20 1.1 times, and n=24n = 24 and n=32n = 32 are 1.3 and 2.2 times slower. The gate is therefore ∣n∣≤12|n| \le 12, or ∣n∣≤32|n| \le 32 with context precision at most 1024 bits, and the loop elsewhere; the tests compare the public result with the loop on both sides of each bound. The exact roots of perfect powers are still decided before either path. Instructions retired per call (53, 128, 512 bits): rsqrt 57, 23 and 35 times fewer, rootn with n=3n = 3 2.1, 3.6 and 11 times fewer.

Trigonometric functions of huge arguments

sin, cos and tan of an argument xx with 2k−1≤∣x∣<2k2^{k-1} \le |x| < 2^k reduce xx modulo π/2\pi/2, which cancels the top kk bits of xx: the reduction needs π\pi to p+k+96p + k + 96 bits for a result of pp bits. The reduced argument lies in (−π/4,π/4)(-\pi/4, \pi/4) and the series needs only the precision of the result, so for k>256k > 256 the enclosure of the reduced argument is rounded outward to p+96p + 96 bits before the series (the reduction and the series are separate precisions). The working precision of the reduction is limited to 8,000,000 bits, so that every argument of the decimal operand range (10999999<2332192910^{999999} < 2^{3321929}) is evaluated; a larger work size is a ResourceLimit certification failure. The decimal driver passes a huge integer operand to Binary exactly (an integer c⋅10ec \cdot 10^e is a dyadic rational) at the result precision, and interval evaluates a point interval by two directed evaluations without the rational index computation.

The cost grows faster than linearly in kk because π\pi at kk bits is computed by binary splitting with a quasi-linear product (a call recomputes π\pi: the cache keeps no entry above 65,536 bits). Native release build, one call of Decimal::sin_ctx in decimal64 (cos and tan cost the same), p = 53 for the binary rows, on a quiet machine, measured at commit bdba3fd (2026-11-20; later multiplication work may lower the numbers by a few percent):

operationsecondsinstructions retiredpeak memory
π\pi at 1,000,000 bits1.531.1e914.6 MB
π\pi at 2,000,000 bits4.5119.6e920.3 MB
π\pi at 3,400,000 bits12.7340.1e928.4 MB
sin of 1E+3000003.888.3e917.2 MB
sin of 1E+60000012.8341.5e922.4 MB
sin of 1E+99999934.9936.7e933.5 MB

The series change alone, sin(2^k) with p=53p = 53 (origin/main before and after):

kkbefore, secondsbefore, instructionsafter, secondsafter, instructions
50,0000.4010.2e90.010.19e9
100,0002.0553.2e90.020.62e9
200,0008.82232.2e90.082.19e9
400,000164 (loaded machine)not measured0.307.78e9

The rows from 1E+300000 upward are in the opt-in table testdata/decimal/ieee/rows/huge_trig_extreme.txt (python3 tools/run_huge_trig_extreme.py); the full gate has the 1E+100000 class.

Asymptotically fast elementary kernels (implemented, with open items)

Status: design and results for #18. The constants (pi, ln 2, ln 10 by binary splitting), the exp enclosure (bit-burst, and by tables at medium precision), the ln enclosure (Newton step and arithmetic-geometric mean) and the sin and cos enclosures are implemented and merged; tan keeps the series. The measured figures are baselines or results of the implemented part; the figures marked “projection” come from a cost model fitted to them and are replaced by measurements as each step lands. The final measurement of the merged kernels is in “Measured result” below. All arguments in this section are paper arguments; none is mechanized.

Problem. Every enclosure above is built from a Taylor or artanh series whose terms are ww-bit numbers, so one evaluation costs O(w/log⁡w)O(w / \log w) full multiplications, that is O(w M(w)/log⁡w)O(w\, M(w) / \log w). At w≈8200w \approx 8200 bits on the native target exp takes 17.8 ms, ln 164 ms and sin 64 ms (before the fixed-point ln and sin branches), while the 8192×81928192 \times 8192-bit product takes 43 µs: exp is about 400 products. The constants are worse when cold: pi takes 742 ms, ln 2 297 ms and ln 10 146 ms at 8192 bits, which a call without a cached constant pays in full (MPFR on the same machine: 0.09 ms for pi, 0.29 ms for ln 2).

Options. (1) Binary splitting of the series of a rational argument, O(M(w)log⁡2w)O(M(w) \log^2 w). (2) Bit-burst: split the argument into chunks of doubling length, evaluate the exponential of each chunk by a series with few terms (the later the chunk, the smaller it is), multiply the results: O(M(w)log⁡2w)O(M(w) \log^2 w) with binary splitting inside and, with the plain fixed-point series inside, one cheap unbalanced product per term (measured: 8192×648192 \times 64 bits 1.8 µs, ×1024\times 1024 bits 6.9 µs, ×8192\times 8192 bits 43 µs). (3) Newton iteration for ln on top of exp. (4) The arithmetic-geometric mean (AGM) for ln and pi, O(M(w)log⁡w)O(M(w) \log w) with large constants. (5) More halving and squaring: the squarings cost one full product each and lose a bit each, so it does not scale.

Choice. Keep the Ziv loop, its working precisions and the exact cases untouched (see Certified elementary functions). Replace only the function that produces the enclosure [L,U][L, U] for a given ww, and only from a per-target precision threshold upward. Every new kernel is a pure function (x,w)↦[L,U](x, w) \mapsto [L, U] of exactly the type the loop already consumes (binary_exp_bounds, binary_ln_bounds, binary_trigonometric_bounds, and the constants), so exp2, exp10, sinh, cosh, pow, rootn and the logarithm family inherit the speed-up, and the recommended functions of #235 (compound, powr, exp2m1, exp10m1, log2p1, log10p1, rSqrt, the π\pi-scaled inverses) are written on the same layer. A kernel returns None for any precondition it cannot verify, and the caller then runs the existing path, so correctness never depends on the new code covering a case.

Integer enclosures. All new kernels work on non-negative integers in units of 2−F2^{-F} with F=w+gF = w + g, using only BinCoeff operations (mul, add, sub_checked, shifts, div_rem_checked, compare, bit_length), which exist on every target, so the same source runs on native, LLVM, Wasm, Wasm-GC and JavaScript. A quantity EE is carried as a pair (ℓ,u)(\ell, u) of integers with the invariant ℓ≤E⋅2F≤u\ell \le E \cdot 2^{F} \le u. Every step produces a new pair from the old ones by monotone operations on non-negative numbers, so the invariant is proved step by step, and the final width u−ℓu - \ell is a computed integer, not an estimate. The last step converts to Binary::make(coeff, exp, w, mode=TowardNegative / TowardPositive), which is what the existing fixed-point series already does.

The ln series loop on limb arrays. The fixed-point series of ln (ln⁡v=2∑kP(k)/(2k+1)\ln v = 2 \sum_k P(k) / (2k + 1) with P(0)=ZP(0) = Z, P(k)=⌊P(k−1)Q/2F⌋P(k) = \lfloor P(k-1) Q / 2^F \rfloor, the terms T(k)=⌊P(k)/(2k+1)⌋T(k) = \lfloor P(k) / (2k + 1) \rfloor and the stop at P(k)<26P(k) < 2^6) computed each term with four Coeff operations that each allocate a result (the product, the shift, the quotient with its remainder, the sum): about four allocations and 3,700 instructions per term at 576 working bits. On the targets with limb rows the loop keeps P, Q, the product, the quotient and the sum in five limb arrays allocated once per call. A term is the exact product by bin_limbs_mul_1 and bin_limbs_addmul_1 (so the same integer as P(k-1) Q), the floor by 2F2^F as one copy pass with the shift F=64w+rF = 64 w + r (limb offset ww, bit offset rr, the case r=0r = 0 apart), the quotient by the odd divisor in place from the top limb, and the sum with a carry. The divisor is at most 2000120001 (the loop stops after 10000 terms), so the running remainder ρ<215\rho < 2^{15} and ρ⋅232+h<247\rho \cdot 2^{32} + h < 2^{47} for a half limb hh: a limb divides by two hardware divisions of its 32-bit halves, no 128-bit helper. Every integer equals the Coeff form’s, so the bounds and their error analysis (above) are unchanged bit for bit; the JavaScript target keeps the Coeff form, since a host BigInt has no limb rows. The tests keep the Coeff loop as the reference and compare the sum and the term count for every FF from 60 to 700 (so every residue of FF modulo 64, in particular F+1F + 1 a multiple of 64 and one below and above it, at one to eleven limbs), for terms whose product has a zero top limb, and the bounds of the whole function on exact values at 380 working precisions.

Shared fixed-point toolkit. The kernels below share one private layer, elementary_toolkit.mbt (issue #368); each piece states its error bound once, and the kernel sections add only what is specific to their series. The extraction is a pure refactor: every kernel returns the same enclosure (L,U)(L, U) as before, bit for bit and None in the same cases, which elementary_toolkit_digest_wbtest.mbt checks with one digest per kernel and working precision (a corpus around every per-target threshold, the multiples of ln⁡2\ln 2 and π/2\pi/2, tiny and large arguments) against a table generated on the kernels before the extraction.

  1. Directed conversion (fixed_scaled_floor, fixed_scaled_exact, fixed_shift, fixed_enclosure). A fixed-point integer NN stands for N/2FN / 2^{F}. fixed_scaled_floor rounds toward −∞-\infty and loses less than one unit; fixed_scaled_exact is None unless the scaling is exact; fixed_enclosure turns an integer pair (ℓ,u)(\ell, u) into floats rounded outward (lower end TowardNegative, upper end TowardPositive), swapping the ends for a negative result.
  2. Bounded cache (BoundedCache[V]: find, insert, capacity as a parameter, oldest entry dropped first). It replaces the three ad-hoc caches (constants, 6 entries per constant; exp tables, 24 sets; factorial coefficients, 64 entries). A cached value is a pure function of its key, so a hit returns the value a recomputation returns.
  3. Term-by-term stage (fixed_series_step, fixed_exp_series). With y=N/2s<1y = N / 2^{s} < 1, t0=2Ft_0 = 2^{F} and ti=⌊⌊ti−1N/2s⌋/i⌋t_i = \lfloor \lfloor t_{i-1} N / 2^{s} \rfloor / i \rfloor, the exact term τi=2Fyi/i!\tau_i = 2^{F} y^i / i! satisfies ti≤τi<ti+3t_i \le \tau_i < t_i + 3 (the deficit did_i obeys di<di−1y/i+1/i+1d_i < d_{i-1} y / i + 1/i + 1). fixed_exp_series sums until a term is below 282^{8} and returns the sum, the last term and its index; the exact value is within tn+3n+3t_n + 3n + 3 above the sum. The fixed exp stage and the bit-burst exp stage use it with their own slack constants (4 and 3), and the burst sin/cos stage uses the step for the real and imaginary parts of eiye^{iy}. binary_ln_unit_fixed_bounds and binary_sin_cos_fixed_series stay apart: their recurrences are in z2z^2 and x2x^2 with different divisors and different tail proofs (an artanh series with ratio z2≤1/9z^2 \le 1/9, an alternating series), not the recurrence above.
  4. Binary splitting (SplitState, split_combine, split_combine_t). A state on [from,to)[from, to) is (p,q,q_shift,t)(p, q, q\_shift, t) with p=∏p(k)p = \prod p(k), q=∏q′(k)q = \prod q'(k), the power of two of q(k)=q′(k)2e(k)q(k) = q'(k) 2^{e(k)} kept apart in q_shift=∑e(k)q\_shift = \sum e(k), and t=q 2q_shift⋅t = q\, 2^{q\_shift} \cdot (partial sum), merged as t=tleft qright2q_shiftright+pleft trightt = t_{\mathrm{left}}\, q_{\mathrm{right}} 2^{q\_shift_{\mathrm{right}}} + p_{\mathrm{left}}\, t_{\mathrm{right}}. The constants (artanh and Chudnovsky series) use q_shift=0q\_shift = 0, the series of eN/2se^{N/2^s} uses q_shift=sq\_shift = s per index from 1 (split_exp_state). All of it is exact integer arithmetic, so the partial sum is the exact rational t/(q 2q_shift)t / (q\, 2^{q\_shift}) and the error bound of a kernel is the bound of its omitted tail alone. The complex stage of sin/cos (SplitComplexState) keeps its own type because it carries two components and rotates the right component by ileaveslefti^{\mathrm{leaves}_{\mathrm{left}}} before the merge; it shares split_combine_t and the products of pp, qq and q_shiftq\_shift. fixed_split_terms gives the number of terms for which the omitted tail of ∑Nk/(k! 2sk)\sum N^k / (k!\, 2^{sk}) is below two units (the proof is in its comment).
  5. Rectangular splitting (rect_plan, rect_powers, rect_sum, rect_inverse_factorials). For a series ∑i<Nciri\sum_{i<N} c_i r^i with nonnegative integer coefficients, r=a/2F<2−kr = a / 2^{F} < 2^{-k}, k≥4k \ge 4, and N=bmN = b m terms, the powers pj=⌊pupv/2F⌋p_j = \lfloor p_u p_v / 2^{F} \rfloor (u+v=ju + v = j) satisfy pj≤2Frj<pj+2p_j \le 2^{F} r^j < p_j + 2. With Pβ=∑j<mcβm+jpjP_\beta = \sum_{j<m} c_{\beta m + j} p_j, Accb−1=Pb−1\mathrm{Acc}_{b-1} = P_{b-1} and Accβ=Pβ+⌊pmAccβ+1/2F⌋\mathrm{Acc}_\beta = P_\beta + \lfloor p_m \mathrm{Acc}_{\beta+1} / 2^{F} \rfloor, the sum satisfies Acc0≤2F∑ciri\mathrm{Acc}_0 \le 2^{F} \sum c_i r^i and its deficit εβ\varepsilon_\beta, in the units of the common denominator of the cic_i, obeys εβ<2∑jcβm+j+2 Accβ+1/2F+1+rmεβ+1\varepsilon_\beta < 2 \sum_j c_{\beta m + j} + 2\,\mathrm{Acc}_{\beta+1} / 2^{F} + 1 + r^m \varepsilon_{\beta+1}. The coefficient sequence is the parameter: rect_inverse_factorials gives ci=N!/i!c_i = N!/i! for ere^r (deficit below 8 units of N!N!, the constant 10 of binary_exp_taylor_fixed); the next kernels pass ci=D/(2i+1)c_i = D/(2i+1) with a common multiple DD (the odd reciprocals of ln⁡\ln and arctan⁡\arctan) or N!/(2i)!N!/(2i)! and N!/(2i+1)!N!/(2i+1)! (sine and cosine, whose alternating signs the caller splits into a positive and a negative series in r2r^2 with nonnegative coefficients). The block size minimizes a cost estimate (rect_block_size) and never changes a result bound; rect_factorial_terms is the term count for factorial decay.
  6. Reduction by ln⁡2\ln 2 (fixed_exp_reduce, fixed_exp_finish), the integer reduction and the closing units of the bit-burst and the table exp, described in the next two sections, and the chunk schedule of the bit-burst (fixed_burst_chunks), used by the exp and the sin/cos kernels.

The guard-bit constants (binary_exp_fixed_guard_bits 16, binary_exp_table_guard_bits 16, binary_exp_burst_guard_bits 48 and the 64 extra bits of the sin/cos burst) stay separate on purpose: they are tuned per kernel (they set the width of the final enclosure, which the width checks compare with the working precision), and changing one changes the enclosure, which this refactor must not do. The mutation hooks (BurstMutation, BurstLnMutation, BurstTrigMutation) stay in the kernels, since they name the kernel’s own proof obligations.

exp, by ln 2 reduction and bit-burst. For finite x≠0x \neq 0 with ∣x∣<230|x| < 2^{30} (larger magnitudes are decided before the loop or fall back), let n=⌊x/ln⁡2⌋n = \lfloor x / \ln 2 \rfloor, found from the cached enclosure of ln⁡2\ln 2 at G=F+bits⁡(n)+2G = F + \operatorname{bits}(n) + 2 bits. Let L=⌊2Gln⁡2⌋/2GL = \lfloor 2^{G} \ln 2 \rfloor / 2^{G} (a dyadic lower bound with 0≤ln⁡2−L≤21−G0 \le \ln 2 - L \le 2^{1-G}) and R=x−nLR = x - nL, computed exactly. If R<0R < 0 or R≥1R \ge 1 the integer nn is corrected by one and RR recomputed. Put Rt=⌊2FR⌋/2FR_t = \lfloor 2^{F} R \rfloor / 2^{F} and δ=(x−nln⁡2)−Rt\delta = (x - n \ln 2) - R_t. Then −∣n∣ 21−G≤δ≤2−F-|n|\,2^{1-G} \le \delta \le 2^{-F} for n≥0n \ge 0 (mirrored for n<0n < 0), so ∣δ∣≤2−F|\delta| \le 2^{-F} by the choice of GG, and since 0≤Rt<10 \le R_t < 1

ex=2n eRt eδ,1−2−F≤eδ≤1+2⋅2−F.e^{x} = 2^{n}\, e^{R_t}\, e^{\delta}, \qquad 1 - 2^{-F} \le e^{\delta} \le 1 + 2 \cdot 2^{-F}.

The factor eδe^\delta costs at most 2⋅3=62 \cdot 3 = 6 units at the end (because eRt<3e^{R_t} < 3), and no sign handling or reciprocal is needed because Rt≥0R_t \ge 0.

Write Rt=∑jyjR_t = \sum_j y_j with yj=Nj/2bj+1y_j = N_j / 2^{b_{j+1}} the bits of RtR_t at positions (bj,bj+1](b_j, b_{j+1}] after the binary point, 0=b0<b1<…0 = b_0 < b_1 < \dots, and bb growing geometrically (factor about 4, first chunk about 16 bits; the constants are tuned per target). Then yj<2−bjy_j < 2^{-b_j}, Nj<2bj+1−bjN_j < 2^{b_{j+1} - b_j}, and eRt=∏jeyje^{R_t} = \prod_j e^{y_j}.

Stage kernel. For y=N/2s<1y = N / 2^{s} < 1 let t0=2Ft_0 = 2^{F} and ti=⌊⌊ti−1N/2s⌋/i⌋t_i = \lfloor \lfloor t_{i-1} N / 2^{s} \rfloor / i \rfloor (the second floor is absent for i=1i = 1), and let τi=2Fyi/i!\tau_i = 2^{F} y^i / i! be the exact terms. By induction ti≤τit_i \le \tau_i (both floors round down), and the deficit di=τi−tid_i = \tau_i - t_i satisfies d1<1d_1 < 1 and di<(di−1 y+1)/i+1d_i < (d_{i-1}\, y + 1)/i + 1, hence d2<2d_2 < 2 and di<4/3+1<3d_i < 4/3 + 1 < 3 for i≥3i \ge 3 (this is the argument of the fixed-point series already in elementary_fixed_exp.mbt, with y<1y < 1 in place of y≤1/8y \le 1/8). Stop at the first nn with tn<28t_n < 2^{8}. For n≥1n \ge 1 the ratio of consecutive exact terms is at most y/(n+1)≤1/2y/(n+1) \le 1/2, so ∑i>nτi≤τn⋅1/21−1/3<τn<tn+3\sum_{i > n} \tau_i \le \tau_n \cdot \frac{1/2}{1 - 1/3} < \tau_n < t_n + 3. With S=∑i=0ntiS = \sum_{i=0}^{n} t_i,

S  ≤  2Fey  ≤  S+tn+3n+3=:S+ey,ey<28+3n+3.S \;\le\; 2^{F} e^{y} \;\le\; S + t_n + 3n + 3 =: S + e_y, \qquad e_y < 2^{8} + 3n + 3 .

Then (ℓ,u)↦(⌊ℓ S/2F⌋,  ⌈u (S+ey)/2F⌉)(\ell, u) \mapsto (\lfloor \ell\, S / 2^{F} \rfloor,\; \lceil u\,(S + e_y) / 2^{F} \rceil) folds the stage into the running product: eye^{y} and the partial product are in the stated intervals, both are non-negative, and multiplication is monotone on non-negative numbers, so the new pair satisfies the invariant. Each stage adds at most ey+2e_y + 2 units of relative width, so with at most JJ stages the final width is below J(28+3nmax⁡+5)+6J (2^{8} + 3 n_{\max} + 5) + 6 units, about 2152^{15} units for w=8192w = 8192; g=48g = 48 guard bits therefore keep the enclosure within 2−(w+6)2^{-(w+6)} relative width, which is the bound the kernel checks (the current series gives about 2−(w+7)2^{-(w+7)}). The kernel computes the true width and returns None when it exceeds that bound.

One full product per chunk. The pair (ℓ,u)(\ell, u) and the stage [l,s][l, s] (l≤ey⋅2F≤sl \le e^{y} \cdot 2^F \le s, both in units of 2−F2^{-F}) are folded as (⌊ℓ l/2F⌋,  ⌊u s/2F⌋+1)(\lfloor \ell\, l / 2^F \rfloor,\; \lfloor u\, s / 2^F \rfloor + 1). Put w=u−ℓw = u - \ell and r=s−lr = s - l. Both are short, and the kernel guarantees it: rr is below 28+3n+52^{8} + 3 n + 5 (the stage bound above), and ww never decreases from one fold to the next (each factor l/2F≥1l / 2^F \ge 1 since ey≥1e^{y} \ge 1), so ww is at most the final width, which the final check limits to 2g−6=2422^{g - 6} = 2^{42} units, one limb. Observed in 150 folds of the kernel at working precisions 2112 and 8256 bits (36 pseudo-random arguments with magnitudes from 2−202^{-20} to 2122^{12}): ww at most 9 bits and rr at most 8 bits. Then u s=ℓ l+ℓ r+w su\, s = \ell\, l + \ell\, r + w\, s exactly, so the upper end is formed from the product ℓ l\ell\, l that the lower end already needs, plus two products by short numbers: one full product and two unbalanced ones instead of two full products. The integers are the same as before, so no error term arises and the width argument above is unchanged. The first chunk starts from ℓ=u=2F\ell = u = 2^F and is the stage itself, (l,s+1)(l, s + 1), without a product.

Cost. A stage with mm-bit numerator at position bb needs nb≈F/(b+log⁡2nb)n_b \approx F / (b + \log_2 n_b) terms, each a product of the shrinking term by an mm-bit integer, a shift and a division by a one-limb integer. For w=8192w = 8192 the first chunk (16 bits) needs about 880 terms, the chunk at 65 to 261 bits about 120, the chunk at 261 to 1045 bits about 31, and the last chunks fewer than 10. The early chunks have too many terms for the fixed-point loop; they are evaluated by binary splitting of ∑i<nNi/(i! 2si)\sum_{i<n} N^i / (i!\, 2^{si}) with exact integers (P,Q,T)(P, Q, T), T=TLQR2s ∣R∣+PLTRT = T_L Q_R 2^{s\,|R|} + P_L T_R, P=PLPRP = P_L P_R, Q=QLQRQ = Q_L Q_R. The enclosure then has no accumulated rounding: ℓ=⌊2FT/(Q2sn)⌋\ell = \lfloor 2^{F} T / (Q 2^{sn}) \rfloor, u=ℓ+3u = \ell + 3 once nn is large enough that Nn2F<n! 2snN^n 2^{F} < n!\, 2^{sn} (an integer comparison on bit lengths), because then the tail is at most 2 τn<22\, \tau_n < 2 units. A stage is estimated (not yet measured) at 8 to 14 full products independent of NN, a fixed-point stage with nn terms costs nn unbalanced products, so the crossover per stage is at nn of a few tens of terms.

The merge of the tree computes the least that the integers need. The values (P,Q,T)(P, Q, T) are exact, so any way of forming them that gives the same integers gives the same enclosure and needs no new error bound; the tree of the stages of exp and of sin and cos forms them with less work than the textbook merge. (1) PLP_L is only read when the node is a left child, and every node of one level has NkN^{k} for the same few kk (the lengths of the ranges of a level differ by at most one), so PP is not carried: the merge reads NℓN^{\ell}, with ℓ\ell the number of indices ≥1\ge 1 of the left range, from a table of the powers of NN that makes each power once as a square or as a product of two smaller ones (about 2log⁡2n2 \log_2 n powers for nn terms, 28 products for the 315 and 105 terms of the first two chunks at 2048 bits, against 418 products of PP). (2) The shift by s ∣R∣s\,|R| and the sum are one operation, Coeff::add_shifted_left, equal to the shift followed by the sum, in one limb array instead of two. (3) A node of two leaves, indices k≥1k \ge 1, is written out: Q=k(k+1)Q = k (k+1), T=N((k+1)2s+N)T = N ((k+1) 2^{s} + N) (for sin and cos the real part is −NN-N N and the imaginary part N(k+1)2sN (k+1) 2^{s}), which replaces two leaf states and the general merge. The tests keep the old tree as a reference and compare the integers: equal for 390 combinations of numerator size (11 to 768768 bits), shift and term count, and the enclosures of the kernels are checked against the series at a working precision 256 bits higher.

Implementation (elementary_burst_exp.mbt). The kernel binary_exp_bounds_burst follows the construction above with these choices: g=48g = 48 guard bits; chunk boundaries at 16,64,256,…16, 64, 256, \dots (first chunk 16 bits, factor 4); a chunk is evaluated by binary splitting when its term count (from the integer bound on 2FNn<n! 2sn2^F N^n < n!\, 2^{sn}, using log⁡2n!≥∑i≤n(bits⁡(i)−1)\log_2 n! \ge \sum_{i \le n} (\operatorname{bits}(i) - 1)) is at least 40, and by the fixed-point series otherwise; ln 2 is requested at the next multiple of 64 above G+2G + 2. The reduced argument comes from one Euclidean division of x2Gx 2^G by ⌊2Gln⁡2⌋\lfloor 2^G \ln 2 \rfloor, so 0≤R<ln⁡20 \le R < \ln 2 with no correction loop. The kernel declines (None, and the series runs) for ∣x∣<2−65|x| < 2^{-65} or ∣x∣≥230|x| \ge 2^{30}, when ∣n∣≥229|n| \ge 2^{29} (the result exponent would approach the limit of the exponent range), when xx has bits below 2−G2^{-G}, and when the computed width exceeds 2−(w+6)2^{-(w+6)} of the value. (Below the table kernel’s ceiling, next section, the table kernel is tried first.) It is used from a per-target working precision, kept with the coefficient thresholds: 1024 bits on Native and LLVM, 1088 on Wasm, 640 on Wasm-GC, 256 on JavaScript (the kernel is slower than the series below roughly 1000 bits on Native, 600 on Wasm-GC; on JavaScript it wins already at 256). The three chunk constants were swept on Native; in a repeat on a quiet machine the chosen point (16, factor 4, split at 40 terms) was the fastest at 8256 bits (1.5 ms against 1.6 to 2.3 ms for the other tried settings) and within about 15 % of the fastest at 2112 bits.

The sweep was repeated after the binary-splitting trees and the fold became cheaper (36 settings, 1024 to 8192 bits of precision, exp and sin, three arguments per size, instructions by the two-count method). The constants (16, 4, 40) stay the best at 8192 bits, but below that a larger first chunk and fewer splitting stages win, and the spread between arguments at one setting is 25 to 30 percent, so a setting is judged by its ratio to the old one on the same argument. On Native the constants are therefore functions of the working precision w: for w <= 3000 the first chunk is 24 bits, the factor 8 and the splitting starts at 80 terms; for 3000 < w <= 6000 the same with factor 4; above 6000 the constants above. Against (16, 4, 40) the instructions per call are 0.69 to 0.99 for sin and 0.81 to 0.98 for exp at working precisions up to 4160, and the two settings are the same code above 6000. The other targets keep (16, 4, 40) at every precision (not measured). A different chunking gives a different but valid enclosure, so the digest rows of the kernels pin the old constants explicitly and new rows pin the kernels with the constants of the working precision.

The sweep for exp alone was repeated after the assembly limb rows became the Native default, in both native states (the default rows and LUNA_FLOATING_LIMBS=c), on five arguments per size (three random values in [1, 2), one near 2−92^{-9}, one at 0.69) and by the same executable with explicit settings, so that the comparison is not across builds (two builds of identical code differ by up to 3.5 percent in instruction counts). The setting (24, 8, 80) loses 6 to 15 percent on random arguments from 2300 bits of precision on, although it gains up to 2048 bits, and (24, 4, 80) loses 4 to 8 percent up to 2300 bits; so exp has its own constants on Native: for w <= 2200 (24, 8, 80), for 2200 < w <= 2700 (24, 8, 120), for 2700 < w <= 6000 (24, 4, 80), above 6000 (16, 4, 40). Against (16, 4, 40), no argument at any measured size (1024, 1536, 2048, 2304, 2560, 2816, 3072, 3584, 4096, 5120, 6144 bits) is above 1.00 in the default state or above 1.01 in the C state. sin and cos keep the constants above.

Evidence for the exp kernel. White-box tests (elementary_burst_exp_wbtest.mbt): the enclosure at ww contains the series enclosure at w+256w + 256 for every argument the kernel accepts in a corpus of 224 values of 60 to 2000 bits with ∣x∣|x| from 2−602^{-60} to 2302^{30}, and for arguments next to multiples of ln⁡2\ln 2, to 229−12^{29} - 1 and to 1−2−k1 - 2^{-k}; it is no wider than the series enclosure at ww; and exp_ctx returns the same value and flags as the Ziv loop run on the series alone, in four rounding directions. Three deliberately wrong variants are caught by the containment test: a bias of 64 units in every stage, 40 terms fewer in the binary-splitting stages, and ln 2 taken with 128 bits fewer for an argument near 2272^{27}. Two obligations are not exercised by such tests: the slack of the fixed-point stages and the units for δ\delta are dominated by the much larger worst-case terms of the other stages, so an enclosure without them still contains the value; their justification is the paper argument above, not the tests. MPFR 4.2.2 comparison: 35,040 rows (precisions 256 to 4096, four rounding directions, arguments from 2−602^{-60} to 2282^{28} and next to multiples of ln⁡2\ln 2) all match; the output is byte-identical on Native, Wasm, Wasm-GC and JavaScript; the random differential run (elem) agrees on 100,000 cases on Native and 20,000 on each other target.

Measured (native, release, this machine). Kernel only, w=p+64w = p + 64 bits, x≈0.7x \approx 0.7: 20 ms to 1.97 ms at 8256 bits, 3.3 ms to 0.67 ms at 4160, 594 to 220 µs at 2112, 112 to 87 µs at 1088; below 1000 bits it is slower (37 to 41 µs at 576). End to end, just bench external quick --ops exp paired and alternating with origin/main (four rounds, the quiet ones last), floating time per call: 8192 bits 20.2 and 20.4 ms against 1.78 and 1.69 ms (paired ratios 9.1 to 12.1), 2048 bits 508 and 517 µs against 187 and 196 µs (2.1 to 2.7), and 53 and 512 bits unchanged within the noise of the machine (0.92 to 1.19). Against the stored MPFR reference of that tool the ratio of the 8192-bit call moves from about 95 to about 8 on the machine of the run (the machine reads about 1.4 times slower than the stored run, so the drift corrected values are about 66 and 5.6).

Ceiling. At 8192 bits the kernel takes the time of 35 to 45 full-size products (43 µs each) and spends most of it in products and divisions of ww-bit numbers. With a multiplication and division kernel three times faster, and everything else unchanged, a first estimate (not measured) is 0.6 to 0.8 ms at 8192 bits and 60 to 80 µs at 2048 bits, which is about 3 to 4 times the MPFR reference (213 µs and 17 µs). The remaining gap would be allocation and the small-integer steps of the fixed-point stages.

exp, by tables and rectangular splitting (medium precision). Below a per-target working precision (1536 to 3072 bits, see below) the enclosure of exe^x comes from binary_exp_bounds_table (elementary_table_exp.mbt), the scheme of Johansson, Efficient implementation of elementary functions in the medium-precision range, ARITH 22 (2015), arXiv:1410.7176, on the integer arithmetic of BinCoeff. Let F=w+gF = w + g rounded up to a multiple of 64 (≥128\ge 128; multiples of 256 above 1024), so g≥16g \ge 16. The reduction to Rt=⌊2FR⌋/2F∈[0,ln⁡2)R_t = \lfloor 2^F R \rfloor / 2^F \in [0, \ln 2) and the residual factor eδe^{\delta} are those of the bit-burst kernel above (3 units below, 6 above in units of 2−F2^{-F}, valid because eRt<3e^{R_t} < 3), the very code of fixed_exp_reduce and fixed_exp_finish (toolkit piece 6). The Taylor series of the remainder is the rectangular splitting of toolkit piece 5 with the coefficients N!/i!N!/i!; its error bound is stated there and not repeated below. Then, with K=k1+k2K = k_1 + k_2 ((k1,k2)=(7,7)(k_1,k_2) = (7,7) for F≤256F \le 256, (6,6)(6,6) up to 1024, (6,5)(6,5) above),

Rt=j12k1+j22K+r,j1=⌊2k1Rt⌋,j2=⌊2K(Rt−j12k1)⌋,0≤r<2−K,R_t = \frac{j_1}{2^{k_1}} + \frac{j_2}{2^{K}} + r,\qquad j_1 = \lfloor 2^{k_1} R_t \rfloor,\quad j_2 = \Bigl\lfloor 2^{K}\bigl(R_t - \tfrac{j_1}{2^{k_1}}\bigr)\Bigr\rfloor,\quad 0 \le r < 2^{-K},

all three parts exact multiples of 2−F2^{-F}, so eRt=T1[j1] T2[j2] ere^{R_t} = T_1[j_1]\, T_2[j_2]\, e^{r} with T1[j]=ej/2k1T_1[j] = e^{j/2^{k_1}} (j≤⌊2k1ln⁡2⌋j \le \lfloor 2^{k_1} \ln 2 \rfloor) and T2[j]=ej/2KT_2[j] = e^{j/2^{K}} (j<2k2j < 2^{k_2}).

Tables. Built lazily, one set per value of FF (at most 24 sets are kept), each entry an integer enclosure L≤2Fej/2k≤HL \le 2^{F} e^{j/2^k} \le H taken from the certified kernels already in the library (binary_exp_bounds_untabled, the bit-burst or series path, at F+8F + 8 bits): L=⌊2F⋅low⌋L = \lfloor 2^F \cdot \mathrm{low} \rfloor, H=⌊2F⋅high⌋+1H = \lfloor 2^F \cdot \mathrm{high} \rfloor + 1. A table is therefore as certified as the kernels it comes from, and a test recomputes every entry of two table sets from the series at F+256F + 256 bits. The tables are not hard-coded.

Taylor series of rr. Write r=a/2Fr = a / 2^F, 0≤a<2F−K0 \le a < 2^{F-K} (so r<2−Kr < 2^{-K}, K≥11K \ge 11 in the shapes above). The number of terms NN is the least with KN+∑i≤N(bits⁡(i)−1)≥F+1K N + \sum_{i \le N} (\operatorname{bits}(i) - 1) \ge F + 1; as N!≥2∑(bits⁡(i)−1)N! \ge 2^{\sum (\operatorname{bits}(i)-1)} and the ratio of consecutive terms is below 1/21/2, the tail satisfies ∑i≥Nri/i!≤2rN/N!≤2−F\sum_{i \ge N} r^i/i! \le 2 r^N/N! \le 2^{-F}: at most one unit. The sum is evaluated by the rectangular (Paterson–Stockmeyer) splitting of toolkit piece 5, with NN rounded up to N′=bmN' = b m, the integer coefficients Ci=N′!/i!C_i = N'!/i! (computed once per N′N') and one final division, E=⌊Acc0/N′!⌋E = \lfloor \mathrm{Acc}_0 / N'! \rfloor; the powers pjp_j and the recurrence for Accβ\mathrm{Acc}_\beta are those defined there, with ej:=2Frj−pj<2e_j := 2^F r^j - p_j < 2 (so e0=e1=0e_0 = e_1 = 0).

Error of the series. The exact counterpart is Acc0∗=N′! 2F∑i<N′ri/i!\mathrm{Acc}^*_0 = N'!\, 2^F \sum_{i<N'} r^i/i!, and every computed quantity is a lower bound of its exact counterpart. Let εβ=Accβ∗−Accβ\varepsilon_\beta = \mathrm{Acc}^*_\beta - \mathrm{Acc}_\beta in units of N′!N'!. The deficit of PβP_\beta is ∑j≥2Cβm+jej/N′!<2∑j≥21/(βm+j)!≤2(e−2)<1.44\sum_{j\ge 2} C_{\beta m+j} e_j / N'! < 2 \sum_{j \ge 2} 1/(\beta m + j)! \le 2(e - 2) < 1.44 (e0=e1=0e_0 = e_1 = 0). In the Horner step the error of pmp_m contributes emAccβ+1∗/(2FN′!)<2er<3.4e_m \mathrm{Acc}^*_{\beta+1} / (2^F N'!) < 2 e^{r} < 3.4 (because Accβ+1∗≤N′! 2Fer\mathrm{Acc}^*_{\beta+1} \le N'!\, 2^F e^{r}), the propagated error pmεβ+1/2F<εβ+1/16p_m \varepsilon_{\beta+1} / 2^F < \varepsilon_{\beta+1}/16, and the floor less than one unit. So εβ<1.44+3.4+1+εβ+1/16\varepsilon_\beta < 1.44 + 3.4 + 1 + \varepsilon_{\beta+1}/16, whence ε<6.2⋅16/15<7\varepsilon < 6.2 \cdot 16/15 < 7 for every block. The final floor loses less than one more unit, and the tail at most one:

E  ≤  2Fer  <  E+10.E \;\le\; 2^F e^{r} \;<\; E + 10 .

Assembly. With the table entries (already in units of 2−F2^{-F}), low=⌊⌊L1L2/2F⌋E/2F⌋−3\mathrm{low} = \lfloor \lfloor L_1 L_2 / 2^F \rfloor E / 2^F \rfloor - 3 and high=⌊⌊H1H2/2F⌋+1)(E+10)/2F⌋+1+6\mathrm{high} = \lfloor \lfloor H_1 H_2 / 2^F \rfloor + 1) (E + 10) / 2^F \rfloor + 1 + 6. All factors are positive, so the floor-and-add-one products are monotone enclosures; the final enclosure is then rounded outward to ww bits. The kernel declines (the older paths run) in the same cases as the bit-burst kernel (∣x∣<2−65|x| < 2^{-65}, ∣x∣≥230|x| \ge 2^{30}, ∣n∣≥229|n| \ge 2^{29}, xx with bits below 2−G2^{-G}) and when the width exceeds 2−(w+6)2^{-(w+6)} of the value. The width of the enclosure is a few dozen units of 2−F2^{-F} (the series 10, the tables 2 each, the reduction 9, the products another factor up to 2), far below the 2F−w−62^{F-w-6} units the check allows.

Why results are bit-identical. The kernel only supplies an enclosure of exe^x to the Ziv loop of exp_ctx and of the functions built on it (exp2, exp10, expm1, pow, compound, powr, the hyperbolic functions, the decimal elementary functions). Correct rounding is unique, so any valid enclosure gives the same value and flags; a different enclosure can only change how many precision steps the loop takes. The proof obligation is therefore exactly the validity of the enclosure, which the analysis above establishes and the white-box tests check against the series at w+256w + 256 bits.

Evidence. elementary_table_exp_wbtest.mbt: containment of the series enclosure at w+256w + 256 for up to 256 arguments of 2−602^{-60} to 2302^{30} at working precisions 53 to 1000, positive and negative; arguments equal to table nodes j/2k1j/2^{k_1}, j/2Kj/2^K and one unit below and above them (remainder at or just off a table boundary); multiples of ln⁡2\ln 2 up to n=106n = 10^6; the Taylor stage on a∈{0,1,2,2F−K−1,2F−K−1,random}a \in \{0, 1, 2, 2^{F-K} - 1, 2^{F-K-1}, \text{random}\} at FF from 80 to 2100 with its width at most 10 units; every entry of two table sets; declined arguments.

Measured (release, this machine, kernel only, x≈0.7x \approx 0.7). Native: 53 bits 7 µs against 10 µs for the series; 100 bits 2.5 against 5.6; 300 bits 4.9 against 12.6 (bit-burst 24); 1000 bits 20 against 42 (burst 69); 2000 bits 94 against 111 (burst 143); 3000 bits 245 against 208. The crossovers (table kernel first up to 1792 bits on Native and LLVM, 2048 on Wasm, 1536 on Wasm-GC, 3072 on JavaScript) are per-target constants beside the bit-burst threshold. Above them the bit-burst kernel (from its own threshold) and the series are unchanged. The cost of the table kernel is dominated by a few dozen BinCoeff operations of 100 to 250 ns each at these sizes, and by the size of the integer coefficients N′!/i!N'!/i! above 2000 bits, which is why it loses there.

ln, by verified Newton step. Write v=m 2kv = m\, 2^{k} with m∈[2−1/2,21/2)m \in [2^{-1/2}, 2^{1/2}), so ln⁡v=kln⁡2+ln⁡m\ln v = k \ln 2 + \ln m. Take any dyadic y0y_0 with about w/2+16w/2 + 16 bits (from the same function at half the precision, recursively, down to the existing series). Correctness does not depend on how good y0y_0 is, only the speed does. Let [Eℓ,Eu][E_\ell, E_u] be the enclosure of ey0e^{y_0} from the kernel above and qℓ=m/Euq_\ell = m / E_u, qu=m/Eℓq_u = m / E_\ell (directed divisions). Since ln⁡\ln is monotone, ln⁡m=y0+ln⁡(m/ey0)∈y0+[ln⁡qℓ,ln⁡qu]\ln m = y_0 + \ln(m / e^{y_0}) \in y_0 + [\ln q_\ell, \ln q_u], and for ∣u∣≤1/2|u| \le 1/2 one has u−u2≤ln⁡(1+u)≤uu - u^2 \le \ln(1 + u) \le u, so

ln⁡m∈[ y0+(qℓ−1)−(qℓ−1)2,    y0+(qu−1) ]\ln m \in \bigl[\, y_0 + (q_\ell - 1) - (q_\ell - 1)^2,\;\; y_0 + (q_u - 1) \,\bigr]

whenever ∣qℓ−1∣,∣qu−1∣≤1/2|q_\ell - 1|, |q_u - 1| \le 1/2 (checked at run time, else None). If ∣ln⁡m−y0∣≤2−(w/2+8)|\ln m - y_0| \le 2^{-(w/2+8)} the quadratic term is below 2−(w+14)2^{-(w+14)} and the width is that of EE. Adding kln⁡2k \ln 2 uses the exact integer product of kk with the dyadic bounds of ln⁡2\ln 2. For ∣m−1∣<2−16|m - 1| < 2^{-16} the existing artanh series has O(w/16)O(w/16) terms and stays in use. The cost is that of one exp at ww plus the recursive call at about w/2w/2 (about 1.51.5 times one exp in total) plus two divisions. Projection at 8192 bits: 3 to 6 ms, against 164 ms today (41 ms projected for the fixed-point branch).

Implementation of the ln step (elementary_burst_ln.mbt). binary_ln_unit_burst_bounds encloses ln⁡v\ln v for 1+2−16<v≤21 + 2^{-16} < v \le 2 (the unit enclosure that binary_ln_bounds adds kln⁡2k \ln 2 to). With inner=w+max⁡(0,2−top⁡(v−1))\mathrm{inner} = w + \max(0, 2 - \operatorname{top}(v - 1)) bits, so that an argument near 1 keeps ww significant bits of the result, y0y_0 is the lower end of the enclosure of ln⁡v′\ln v' at inner/2+16\mathrm{inner}/2 + 16 bits, where v′v' is vv rounded to that many bits (the same function one level down, so the recursion ends in the series below the threshold); [Eℓ,Eu][E_\ell, E_u] is the exp kernel at inner+8\mathrm{inner} + 8 bits; the two divisions and the final operations use inner+24\mathrm{inner} + 24 bits with directed rounding, and the result is rounded outward to ww bits. It declines (and the series runs) for v≤1+2−16v \le 1 + 2^{-16} or v>2v > 2, when ∣q−1∣>1/2|q - 1| > 1/2, and when the width of the result exceeds 8 units of 2−inner2^{-\mathrm{inner}}. The thresholds, kept with the other coefficient-kernel thresholds, are 1152 bits on Native and LLVM, 1280 on plain Wasm and on JavaScript and 576 on Wasm-GC (the kernel is slower than the fixed-point series below roughly 1000 bits on Native, 500 on Wasm-GC and 1200 on Wasm and JavaScript).

Evidence for the ln step. White-box tests (elementary_burst_ln_wbtest.mbt): for every argument of a corpus of 158 values in (1,2](1, 2] (random, near 1 down to 2−1002^{-100}, near 2, 3/2, 5/4) that the kernel accepts, the enclosure at ww contains the series enclosure at w+256w + 256; it is no wider than the series enclosure at ww; ln_ctx returns the same value and flags as the Ziv loop on the series alone in four rounding directions; and the kernel declines out of range. Two deliberately wrong variants are caught: a bias of 8 units in the lower end, and a poor start value (about w/8w/8 bits) with the quadratic term dropped. A poor start value with the quadratic term kept only widens the enclosure and the test checks that it is still valid. One obligation is not reached by the tests: dropping the quadratic term with the real start value is not detected, because u2≈2−(w+26)u^2 \approx 2^{-(w+26)} is below the width of the exp enclosure; its justification is the paper argument (u−u2≤ln⁡(1+u)u - u^2 \le \ln(1+u) for u≥−1/2u \ge -1/2), not the tests. MPFR 4.2.2 comparison: 13,200 rows (precisions 256 to 4096, four rounding directions, arguments with binary exponents from −1000-1000 to 10510^5, near 1 and near powers of two; the threshold was set to 256 for this run so that every row used the kernel) all match, and the output is byte-identical on Native, Wasm, Wasm-GC and JavaScript.

Measured for the ln step (native, release, this machine, on the 64-bit limbs, the Karatsuba and the division of #324, #326 and #328). Kernel only, w=p+64w = p + 64 bits, vv random in [1,2)[1, 2), against the fixed-point series of #319 (the machine was loaded, the ratios are the figure): 23.0 ms to 2.24 ms at 8256 bits (10.3 times), 3.27 ms to 0.75 ms at 4160 (4.4), 581 to 309 µs at 2112 (1.9), equal at 1024; slower below about 1000 bits (0.5 to 0.8 times at 384 to 768). End to end, just bench external quick --ops ln paired and alternating with origin/main, four rounds on a loaded machine (load average about 10), the floating time per call: 8192 bits 27.0, 25.6, 25.6 and 28.0 ms against 2.43, 2.40, 2.57 and 2.44 ms (paired ratios 11.1, 10.7, 10.0 and 11.5), 2048 bits 695, 565, 639 and 856 µs against 300, 295, 378 and 365 µs (2.3, 1.9, 1.7 and 2.35), 512 and 53 bits unchanged (0.98 to 1.07 at 53 bits, 0.99 to 1.36 at 512 bits, where the code path is the old one and the machine was noisy). The raw ratio to the stored MPFR medians (floating time of the day over the stored MPFR median) of the 8192-bit call goes from 221 to 243 to 21 to 22, and of the 2048-bit call from 37 to 57 to 20 to 25. MPFR re-measured on the machine at that time reads 1.9 to 2.0 times slower than the stored run at 8192 bits and 1.65 times at 2048 bits (the load), so the drift-corrected ratios are about 10.7 to 11.4 at 8192 bits and about 12 to 15 at 2048 bits; an earlier run on a quiet machine gave 11.5 to 13.6 at 8192 bits (on the previous division kernel).

ln, by the arithmetic-geometric mean. For the outermost ln call (never for the constants, which the mean needs) and for 1+2−16<v≤21 + 2^{-16} < v \le 2 the enclosure of ln⁡v\ln v is built from ln⁡s=π/(2 AG(1,4/s))\ln s = \pi / (2\, \mathrm{AG}(1, 4/s)) up to a model term, with s=v 2ms = v\, 2^{m}, m=⌈p/2⌉+2m = \lceil p/2 \rceil + 2 (so s>2p/2+2s > 2^{p/2 + 2} and 4/s2<2−(p+2)4/s^2 < 2^{-(p+2)}), ln⁡v=ln⁡s−mln⁡2\ln v = \ln s - m \ln 2.99 R. P. Brent, “Fast multiple-precision evaluation of elementary functions”, J. ACM 23(2), 1976 (bit-burst and the AGM logarithm; citation to be confirmed against the paper). The truncation bound of the AGM kernel is taken from DLMF 19.8.5 and 19.9.2 (see “ln, by the arithmetic-geometric mean”), not from this paper. MPFR’s log.c documents the same algorithm and is secondary evidence only. Every step below has a stated bound; none uses MPFR’s constants.

  1. The argument. x=4/s=(4/v) 2−mx = 4/s = (4/v)\, 2^{-m}: one division rounded to nearest at pp bits, relative error at most 2−p2^{-p}, then an exact shift. AG\mathrm{AG} is increasing in each argument and homogeneous of degree one (both maps (a,b)↦((a+b)/2,ab)(a, b) \mapsto ((a+b)/2, \sqrt{ab}) are), so for θ≥0\theta \ge 0: AG(1,x)≤AG(1,x(1+θ))≤AG(1+θ,x(1+θ))=(1+θ) AG(1,x)\mathrm{AG}(1, x) \le \mathrm{AG}(1, x(1+\theta)) \le \mathrm{AG}(1+\theta, x(1+\theta)) = (1+\theta)\, \mathrm{AG}(1, x), and symmetrically for θ<0\theta < 0: the relative error of xx moves AG\mathrm{AG} by at most as much.
  2. The iteration. u′=uvu' = \sqrt{u v}, v′=(u+v)/2v' = (u+v)/2 from (x,1)(x, 1), every product, square root and sum rounded to nearest at pp bits (relative error δ=2−p\delta = 2^{-p} each). The halving of the sum is exact and is made by changing the exponent of the already normalized coefficient, and the root is the correctly rounded one, taken from the limb-array kernel of the public square root (the context form gives the same value and costs 39 percent more at 2140 bits); neither changes a value, so the induction below is that of the plain iteration. With the exact sequence (Uk,Vk)(U_k, V_k) and uk=Uk(1+ak)u_k = U_k (1 + a_k), vk=Vk(1+bk)v_k = V_k (1 + b_k), ∣ak∣,∣bk∣≤εk|a_k|, |b_k| \le \varepsilon_k: the product has (1+a)(1+b)(1+η1)(1+a)(1+b)(1+\eta_1), the root halves the exponent of that factor and adds one rounding, the sum is bounded by (1+ε)(1+η3)(1 + \varepsilon)(1 + \eta_3) and halving is exact, so εk+1≤εk+2δ+O(δ εk)\varepsilon_{k+1} \le \varepsilon_k + 2\delta + O(\delta\, \varepsilon_k), and εn≤(3n+4)δ\varepsilon_n \le (3 n + 4)\delta for n<64n < 64 (MPFR’s analysis of the same iteration, with the Higham calculus, gives 3n/23n/2; ours is looser by 2).
  3. Stopping. After each iteration stop when ∣u−v∣<2top⁡(v)−p+3≤16 δv|u - v| < 2^{\operatorname{top}(v) - p + 3} \le 16\,\delta v (tested on exponents; when the exponents of uu and vv differ by 2 or more the two differ by more than half of the larger, which is not below 16 δv16\,\delta v, so the difference is formed only when they differ by at most 1). A tolerance of one unit would never stop: two nearest-rounded means can stay one unit apart. AG(Un,Vn)\mathrm{AG}(U_n, V_n) lies between UnU_n and VnV_n, which differ by at most 16 δv+2εnv(1+εn)16\,\delta v + 2 \varepsilon_n v (1 + \varepsilon_n), so ∣AG(1,4/s)−vn∣≤e vn|\mathrm{AG}(1, 4/s) - v_n| \le e\, v_n with e=(9n+30)δe = (9 n + 30)\delta (the +1+1 from step 1 included). The code forms vn(1±e)v_n (1 \pm e) with directed products.
  4. The model term. With F=π/(2 AG(1,4/s))F = \pi / (2\, \mathrm{AG}(1, 4/s)) the lower end uses ln⁡s≥F(1−4/s2)\ln s \ge F (1 - 4/s^2) and the upper end ln⁡s≤F\ln s \le F. Both follow from two equations of the NIST Digital Library of Mathematical Functions, for 0<k<10 < k < 1 and k′=1−k2k' = \sqrt{1 - k^2}: DLMF 19.8.5, K(k)=π/(2 AG(1,k′))K(k) = \pi / (2\, \mathrm{AG}(1, k')), and DLMF 19.9.2, 1+k′2/8<K(k)/ln⁡(4/k′)<1+k′2/41 + k'^2/8 < K(k) / \ln(4/k') < 1 + k'^2/4. Put k′=4/sk' = 4/s with s>4s > 4 (so 0<k′<10 < k' < 1 and ln⁡(4/k′)=ln⁡s\ln(4/k') = \ln s): F=K(k)F = K(k) by 19.8.5 and 19.9.2 reads (1+2/s2)ln⁡s<F<(1+4/s2)ln⁡s(1 + 2/s^2) \ln s < F < (1 + 4/s^2) \ln s. Hence ln⁡s<F\ln s < F, and ln⁡s>F/(1+4/s2)>F(1−4/s2)\ln s > F / (1 + 4/s^2) > F (1 - 4/s^2) since 1/(1+x)>1−x1/(1 + x) > 1 - x for x>0x > 0. The same inequality gives the lower bound F−ln⁡s>2ln⁡s/s2F - \ln s > 2 \ln s / s^2 as a by-product. The range is s>4s > 4, and the kernel’s s>2p/2+2s > 2^{p/2 + 2} with p≥64p \ge 64 satisfies it. Numerically (exact decimal arithmetic, s=2ks = 2^k, k=1…40k = 1 \ldots 40) the ratio (F−ln⁡s)/(4ln⁡s/s2)(F - \ln s) / (4 \ln s / s^2) is between 0.532 and 0.964, inside the interval (0.5,1)(0.5, 1) that 19.9.2 predicts (the values for k=1,2k = 1, 2, that is s≤4s \le 4, are also inside, though DLMF does not cover them). The code subtracts F 2−(p−2)F\, 2^{-(p-2)}, sixteen times the term 4/s2<2−(p+2)4/s^2 < 2^{-(p+2)} that the lemma needs, and the error margin eFe F of step 3 is more than a hundred times that term: the factor is slack, not a need, and is kept as it is.
  5. The constants and the result. πl≤π≤πu\pi_l \le \pi \le \pi_u at p+8p + 8 bits and ln⁡2\ln 2 at p+16p + 16 bits (the cached enclosures), Fl=πl/(2vn(1+e))F_l = \pi_l / (2 v_n (1 + e)) and Fu=πu/(2vn(1−e))F_u = \pi_u / (2 v_n (1 - e)) by directed divisions, mln⁡2m \ln 2 by directed products with the integer m<2⌈log⁡2p⌉m < 2^{\lceil \log_2 p \rceil}, and the subtraction directed. Cancellation: FF and mln⁡2m \ln 2 are about 0.35p0.35 p and the result about 2lead2^{\mathrm{lead}} with lead≥−16\mathrm{lead} \ge -16, so about log⁡2(0.35p)+16≤28\log_2(0.35 p) + 16 \le 28 bits are lost; they are paid once in the working precision p=w+(2−lead)+bits⁡(w)+16p = w + (2 - \mathrm{lead}) + \operatorname{bits}(w) + 16 (no restart, as MPFR does). The width of the result is at most 2−(w+3)2^{-(w + 3)} by this choice and is checked (as in the Newton step): a wider result returns None and the Newton step or the series runs.

Cost. nn iterations of one product, one square root and one sum: n=18n = 18 at 2112 bits and 22 at 8256 bits (exact decimal AGM of (1,4/2p/2+1)(1, 4/2^{p/2+1}), 14 at 512), about 2log⁡2p−42 \log_2 p - 4. Per call: nn products, nn square roots, 3 divisions (one for 4/v4/v, two for FF), about 5 products by short numbers, the two cached constants. In multiplication units (MM of the same side, the 0.11.0 baseline) this is about 66 at 2048 bits and 61 at 8192 against 178 and 133 for the Newton step and 65 and 55 for MPFR: the count equals MPFR’s, so the ratio to MPFR stays at the ratio of the product and square-root kernels (about 4).

Choice of path. The mean costs the same for every argument in (1+2−16,2](1 + 2^{-16}, 2], the series of an argument 1+d1 + d with ∣d∣≈2−k|d| \approx 2^{-k} needs about p/(2k)p/(2k) terms: they meet at k≈16k \approx 16 at 2048 bits, which is the existing bound binary_ln_burst_near_one_bits, so the argument ranges of the Newton step and of the mean are the same, and below 1+2−161 + 2^{-16} the series remains. The threshold binary_ln_agm_min_precision (native: 1152 working bits, per target; it was 640 before the series ran on limb arrays, which made the series cost 0.27 to 0.39 of its former cost at 117 to 576 working bits) is chosen from the instruction counts below and from a re-measurement on both limb-row tiers (the series below 768 working bits, the Newton step from 768 to 1151, the mean from 1152; binary_ln_entry_min_precision is 768); the other targets are not measured and keep the kernel off (the constant is 2302^{30} there), so their results are unchanged. The Newton step stays for working precisions below the threshold and as the fallback of the width check.

Result (native, instructions retired per call, Newton step before and mean after):

ln precision (bits)Newton stepmeanratio
512501,445509,3271.016
640680,378566,5710.833
10241,536,465817,7210.532
20484,096,6761,798,5740.439
409610,223,9755,172,6410.506
819227,924,30717,172,6210.615

The enclosure is verified by the same tests as the Newton step (containment of the exact value shown by the series at 256 bits more, no wider than the Newton enclosure, declined outside its range, mutated kernels caught). The results of ln, log2, log10 and the inverse hyperbolic functions are correctly rounded from either enclosure, so they do not depend on which one ran.

sin and cos, by complex bit-burst. With H=⌊2Gπ/2⌋/2GH = \lfloor 2^{G} \pi/2 \rfloor / 2^{G}, G=F+bits⁡(n)+2G = F + \operatorname{bits}(n) + 2, the quadrant integer n=round⁡(x/H)n = \operatorname{round}(x / H) and R=x−nHR = x - nH (exact, ∣R∣≤0.8|R| \le 0.8 after a correction of nn), the true reduced argument r=x−nπ/2r = x - n \pi/2 satisfies ∣r−R∣≤∣n∣ 21−G≤2−F|r - R| \le |n|\,2^{1-G} \le 2^{-F}. Sine and cosine are 1-Lipschitz, so sin⁡r∈sin⁡R±2−F\sin r \in \sin R \pm 2^{-F} and likewise for the cosine; truncating ∣R∣|R| to FF bits costs one more unit. The quadrant n mod 4n \bmod 4 maps (sin⁡r,cos⁡r)(\sin r, \cos r) to the result, as in binary_reduced_trigonometric_bounds. For y=N/2s<1y = N/2^s < 1 the real and imaginary parts of the series of eiye^{iy} are the even and odd terms of the same sequence tit_i as above, with signs (−1)⌊i/2⌋(-1)^{\lfloor i/2 \rfloor}, so a stage costs the same as an exp stage and gives both cos⁡y\cos y and sin⁡y\sin y. The deficits satisfy the same bound di<3d_i < 3, and each of the two alternating series has terms that decrease in size (y2/((i+1)(i+2))<1y^2 / ((i+1)(i+2)) < 1), so the tail after tn<28t_n < 2^{8} is at most tn+3t_n + 3 in size and the enclosure is ScosS_{\mathrm{cos}} or Ssin±(tn+3n+3)S_{\mathrm{sin}} \pm (t_n + 3n + 3). Stages are folded by rotation, (C,S)←(Cc−Ss,  Sc+Cs)(C, S) \leftarrow (C c - S s,\; S c + C s), with four products and interval bounds on non-negative integers; all partial angles lie in [0,0.8][0, 0.8], so all four factors are non-negative and the difference of bounds is checked to be non-negative. Because the merge costs four full products per stage, the stages are fewer than for exp (factor 4 to 8 between chunk boundaries), and the last stage computes only the requested one of the two values. For ∣R∣<2−16|R| < 2^{-16} the existing series stays. Projection at 8192 bits: 4 to 6 ms, against 64 ms today (16 ms projected for the fixed-point branch); tan and the π\pi-scaled functions follow.

Implementation of the sin and cos step (elementary_burst_trig.mbt). binary_trig_bounds_burst (hooked into binary_trigonometric_bounds for sin and cos; tan keeps the series) follows the construction above for 2−64≤∣x∣<240962^{-64} \le |x| < 2^{4096}. With F0=w+112F_0 = w + 112 and G=F0+max⁡(1,top⁡(x))+2G = F_0 + \max(1, \operatorname{top}(x)) + 2, the nearest integer nn to ∣x∣/H|x| / H, H=⌊2Gπ/2⌋/2GH = \lfloor 2^{G} \pi/2 \rfloor / 2^{G}, comes from one Euclidean division of integers, R=∣x∣−nHR = |x| - nH is exact with ∣R∣≤H/2|R| \le H/2, and the true reduced argument r=∣x∣−nπ/2r = |x| - n\pi/2 satisfies ∣r−R∣≤n 21−G≤2−(F0+1)|r - R| \le n\, 2^{1-G} \le 2^{-(F_0+1)}. The working scale is F=w+48+lzF = w + 48 + \mathrm{lz} with lz=max⁡(0,2−top⁡(R))\mathrm{lz} = \max(0, 2 - \operatorname{top}(R)) (declined above 64, so RR near a multiple of π/2\pi/2 keeps ww significant bits of a sine), and Rt=⌊2F∣R∣⌋/2FR_t = \lfloor 2^{F} |R| \rfloor / 2^{F} satisfies ∣r−sign⁡(R)Rt∣≤1.5⋅2−F|r - \operatorname{sign}(R) R_t| \le 1.5 \cdot 2^{-F}, so by the Lipschitz bound the sine and cosine of rr are within 2 units of those of sign⁡(R)Rt\operatorname{sign}(R) R_t. RtR_t is cut into chunks at 16, 64, 256, … bits as for exp. A chunk is a ball: a midpoint and a radius in units of 2−F2^{-F}. The fixed-point stage sums the even terms of the series of eiye^{iy} for the cosine and the odd ones for the sine, with signs +−+−…+ - + - \dots in each, from the same sequence tit_i as in the exp stage (deficit below 3); each of the two alternating series decreases in size, so each sum is within 3n+tn+33n + t_n + 3 of its value. The binary-splitting stage keeps a complex state: the leaf of an index i≥1i \ge 1 is (0,N)(0, N) (the factor iNi N), p=Nleavesp = N^{\mathrm{leaves}}, q=∏iq = \prod i, and t=tLqR2s lenR+ileavesLpLtRt = t_L q_R 2^{s\,\mathrm{len}_R} + i^{\mathrm{leaves}_L} p_L t_R, where multiplying by imi^m only permutes and negates the two components; the partial sums are exact rationals, the floors lose less than 1 unit, and the omitted terms are below 2 units, so each part is a ball of radius 2. The product of two balls with midpoints a,ba, b and radii α,β\alpha, \beta has midpoint ⌊ab/2F⌋\lfloor a b / 2^F \rfloor and radius ⌈(aβ+bα+αβ)/2F⌉+2\lceil (a \beta + b \alpha + \alpha \beta)/2^F \rceil + 2, and the stages are folded by rotation, C′=Cc−SsC' = C c - S s and S′=Sc+CsS' = S c + C s (four ball products; the first stage is not multiplied at all, and the last fold forms only the component the result reads, two ball products), with the midpoint of the difference required to be non-negative. The quadrant n mod 4n \bmod 4 and the signs of xx and RR select which component is the result. It declines for ∣x∣<2−64|x| < 2^{-64}, ∣x∣≥24096|x| \ge 2^{4096}, when the reduced argument is smaller than 2−622^{-62}, and when the width exceeds 2−(w+5)2^{-(w+5)} of the value. The thresholds are 1536 bits on Native and LLVM, 2112 on plain Wasm, 640 on Wasm-GC and 256 on JavaScript (the kernel is slower than the series below roughly 1500 bits on Native, 2000 on Wasm and 600 on Wasm-GC; on JavaScript it wins from 256).

The binary-splitting stages by the real series of the sine. A stage whose chunk has at least split_min_terms terms no longer evaluates the complex series eiye^{iy}, y=N/2s<1y = N/2^s < 1 (a tree with two signed components and five products per node), but the real series sin⁡y=y S(y2)\sin y = y\, S(y^2), S(z)=∑k≥0(−z)k/(2k+1)!S(z) = \sum_{k \ge 0} (-z)^k / (2k+1)!, as a tree over the indices k=0…n′−1k = 0 \ldots n'-1 with p(k)=−N2p(k) = -N^2, q(k)=2k(2k+1) 22sq(k) = 2k (2k+1)\, 2^{2s} (k≥1k \ge 1) and a signed TT, merged exactly as the tree of eye^{y} (powers of N2N^2 from the power table, sign (−1)ℓ(-1)^{\ell} from the parity of the left leaves, the signed merge of split_combine_t). The exact partial sum is T/(Q 2qshift)T / (Q\, 2^{q_{\mathrm{shift}}}) and the sine is NT/(2s Q 2qshift)N T / (2^{s}\, Q\, 2^{q_{\mathrm{shift}}}), the same rational as the imaginary part of the complex tree over 2n′2n' indices (the test compares the two as integers).

Term count. Let nn be the term count of the exponential series from the integer bound of the exp stage: 2FNn<n! 2sn2^F N^n < n!\, 2^{sn}, which follows from F+mn≤L(n)+snF + m n \le L(n) + s n with m=bits⁡(N)m = \operatorname{bits}(N) and L(n)=∑i≤n(bits⁡(i)−1)≤log⁡2n!L(n) = \sum_{i \le n} (\operatorname{bits}(i) - 1) \le \log_2 n!. The bound holds for every larger count: going from nn to n+1n+1 the left side grows by m≤sm \le s (since N<2sN < 2^s gives m≤sm \le s) and the right side by bits⁡(n+1)−1+s≥s\operatorname{bits}(n+1) - 1 + s \ge s, so F+m(n+1)≤L(n+1)+s(n+1)F + m(n+1) \le L(n+1) + s(n+1). The first omitted term of the sine series has the exponent 2n′+12n' + 1, and with n′=⌊n/2⌋n' = \lfloor n/2 \rfloor this is at least nn, so that term is y2n′+1/(2n′+1)!<2−Fy^{2n'+1} / (2n'+1)! < 2^{-F}, below one unit. The series alternates and its terms decrease (y2<1y^2 < 1, the ratio of consecutive terms is y2/((2k+2)(2k+3))<1y^2 / ((2k+2)(2k+3)) < 1), so the whole tail is below one unit in size; the floor of the quotient loses less than one unit; the ball [q−1,q+3][q - 1, q + 3] (midpoint q+1q + 1, radius 2, as for the complex stage) contains sin⁡y\sin y.

The cosine of the stage. The fold needs the cosine too. Every stage satisfies 0<y≤π/20 < y \le \pi/2 (the chunks are parts of the reduced argument, at most π/4\pi/4), so cos⁡y=+1−sin⁡2y\cos y = +\sqrt{1 - \sin^2 y} without a sign question, and the root is well conditioned there (sin⁡y/cos⁡y≤1\sin y / \cos y \le 1 for y≤π/4y \le \pi/4), so no bits are lost near 00 (where cos⁡y≈1\cos y \approx 1) and the argument never approaches π/2\pi/2. With the sine ball [sℓ,sh][s_\ell, s_h] in units of 2−F2^{-F} (clamped to sℓ≥0s_\ell \ge 0 and sh≤2Fs_h \le 2^F, both true for the sine of y∈(0,π/2]y \in (0, \pi/2]), the function c(s)=22F−s2c(s) = \sqrt{2^{2F} - s^2} decreases in ss, so for every s∈[sℓ,sh]s \in [s_\ell, s_h]: ⌊22F−sh2⌋≤c(s)≤⌊22F−sℓ2⌋+1\lfloor \sqrt{2^{2F} - s_h^2} \rfloor \le c(s) \le \lfloor \sqrt{2^{2F} - s_\ell^2} \rfloor + 1, two exact integer square roots, no derivative bound; for sℓ=0s_\ell = 0 the upper end is 2F2^F. For a split stage sℓ>0s_\ell > 0 always (sin⁡y⋅2F≥2F−s\sin y \cdot 2^F \ge 2^{F-s} and a split stage has s≪Fs \ll F), the clamp is only a guard. The cosine ball is the interval of these two ends (midpoint the floor of their mean, radius the rest). The fixed-point stages and the fold by rotation are unchanged.

Evidence for the real stage. The two trees are compared as integers (the real sine tree against the imaginary part of the complex tree, 390 combinations of numerator size, shift and term count), the stage balls against the balls of the complex stage kept in the test file as the reference (they intersect, and the sine radius is the same), the kernel against the series enclosure at working precision +256 bits by the existing burst tests, and the rounding rules by a deterministic test of the cosine ball: for a given ss the ends are the floor of the root and the floor plus one (so a cosine strictly between them is enclosed only with the plus one), for s=0s = 0 the end is 2F2^F; the mutations “ends swapped” and “plus one omitted” change the ends. Instructions per call of sin and cos at 2048, 4096 and 8192 bits: 0.68 to 0.83 of before on three arguments per size.

Evidence for the sin and cos step. White-box tests (elementary_burst_trig_wbtest.mbt): for every argument the kernel accepts in a corpus of 354 values (60 to 2000 bits, ∣x∣|x| from 2−602^{-60} to 21002^{100}, both signs, and the neighbourhood of nine multiples of π/2\pi/2 for four precisions) and for both functions, the enclosure at ww contains the series enclosure at a precision 256 bits higher (and high enough for the series to certify the quadrant); it is no wider than the series enclosure; sin_ctx and cos_ctx return the value and flags of the series enclosure rounded at twice the precision, in four rounding directions; and the kernel declines out of its range. Three deliberately wrong variants are caught: a bias of 2642^{64} units in every stage, 40 terms fewer in the binary-splitting stages, and π\pi taken with 200 bits fewer for an argument near 2402^{40}. A bias below about 2402^{40} units is absorbed by the 48 guard bits and the final rounding, so the tests cannot see it; likewise the radius of the fixed-point stages and the 2 units of the angle error are dominated by worst-case terms elsewhere, so removing them leaves an enclosure that still contains the value: their justification is the paper argument above, not the tests. MPFR 4.2.2 comparison: 23,424 rows for each of sin and cos (precisions 256 to 4096, four rounding directions, arguments from 2−602^{-60} to 210002^{1000}, and neighbours of multiples of π/2\pi/2; the thresholds were set to 256 for this run so that every row used the kernel) all match, and the output is byte-identical on Native, Wasm, Wasm-GC and JavaScript.

Measured for the sin and cos step (native, release, this machine, with the Karatsuba limbs and the division of #326 and #328). Kernel only, w=p+40w = p + 40 bits, x≈0.7x \approx 0.7 for the sine and x≈16x \approx 16 to 3232 for the cosine, against the reduction and fixed-point series of #321: sine 8.37 ms to 1.39 ms at 8256 bits, 1.58 ms to 0.57 ms at 4160, 338 to 239 µs at 2112, equal at 1536; cosine 5.31 ms to 1.20 ms at 8256, 1.01 ms to 0.47 ms at 4160; slower below about 1500 bits (0.5 to 0.9 times at 256 to 1280). End to end, just bench external quick --ops sin paired and alternating with origin/main, four rounds on a quiet machine, floating time per call: 8192 bits 6.92, 6.66, 6.73 and 6.66 ms against 1.47, 1.32, 1.29 and 1.38 ms (paired ratios 4.7, 5.1, 5.2 and 4.8), 2048 bits 282, 288, 276 and 268 µs against 203, 195, 183 and 204 µs (1.4, 1.5, 1.5 and 1.3), and 512 and 53 bits unchanged (0.89 to 1.12, the old code path). The raw ratio to the stored MPFR medians (floating time of the day over the stored MPFR median) of the 8192-bit call goes from 34 to 35 to 6.5 to 7.4, and of the 2048-bit call from 19 to 20 to 13 to 14; the machine reads about 1.45 times slower than the stored run (MPFR re-measured on it), so the drift-corrected ratios are about 4.5 to 5.1 at 8192 bits and about 9 to 10 at 2048 bits.

Constants by binary splitting. pi, ln 2 and ln 10 are computed once per working precision and cached, but a first call pays the cold cost above. Binary splitting gives O(M(w)log⁡2w)O(M(w) \log^2 w) with rigorous bounds:

π=42688010005 QT,ln⁡2=18 artanh⁡126−2 artanh⁡14801+8 artanh⁡18749,ln⁡10=3ln⁡2+2artanh⁡19,\pi = \frac{426880\sqrt{10005}\, Q}{T}, \qquad \ln 2 = 18\,\operatorname{artanh}\tfrac1{26} - 2\,\operatorname{artanh}\tfrac1{4801} + 8\,\operatorname{artanh}\tfrac1{8749}, \qquad \ln 10 = 3 \ln 2 + 2\operatorname{artanh}\tfrac19 ,

where (P,Q,T)(P, Q, T) come from the Chudnovsky series (alternating, about 46 bits per term) and artanh⁡(1/k)=∑j1/((2j+1)k2j+1)\operatorname{artanh}(1/k) = \sum_j 1/((2j+1)k^{2j+1}).

Implementation (elementary_constants_split.mbt). The state of a series on an index range is (p,q,t)(p, q, t) with p=∏p(k)p = \prod p(k), q=∏q(k)q = \prod q(k) and t=q⋅(partial sum)t = q \cdot (\text{partial sum}), combined as t=qRtL+pLtRt = q_R t_L + p_L t_R; the artanh series has p(j)=2j−1p(j) = 2j - 1 and q(j)=(2j+1)k2q(j) = (2j + 1) k^2, which telescope to 1/((2j+1)k2j)1/((2j+1) k^{2j}), and the Chudnovsky series has p(k)=(6k−5)(2k−1)(6k−1)p(k) = (6k-5)(2k-1)(6k-1), q(k)=k3 6403203/24q(k) = k^3\, 640320^3 / 24 and the leaf t=±p(k)(A+Bk)t = \pm p(k)(A + Bk). Only the Chudnovsky tt is signed, so a sign-and-magnitude wrapper over the unsigned BinCoeff suffices and the code is the same on every target. The partial sum t/qt/q is exact; the only roundings are the final directed divisions and 10005\sqrt{10005} (directed sqrt_ctx), done at w+16w + 16 bits, and the result is rounded outward to ww bits.

Tail bounds. For artanh⁡(1/k)\operatorname{artanh}(1/k) with K=k2K = k^2 take NN terms with KN≥2F+9K^N \ge 2^{F+9}, F=w+16F = w + 16 (using ⌊log⁡2K⌋\lfloor \log_2 K \rfloor): the first omitted term is at most 2−(F+9)2^{-(F+9)} and the omitted terms are positive and shrink by at least 1/K≤1/41/K \le 1/4, so they sum to less than 2−(F+8)2^{-(F+8)}, which is added to the upper end. For Chudnovsky the ratio of the factorial parts of consecutive terms is 8(6k+1)(6k+3)(6k+5)/(k+1)3≤17288(6k+1)(6k+3)(6k+5)/(k+1)^3 \le 1728, the linear factor grows by at most 41.11 from k=0k = 0 to 11 and by less than 2 after that, and 6403203>257.8640320^3 > 2^{57.8}, so the ratios are below 2−41.72^{-41.7} and then 2−46.12^{-46.1}, the terms decrease in size, alternate in sign, and the first is below 2242^{24}. The omitted sum from index NN is therefore at most the size of term NN, below 2−17−46(N−1)2^{-17 - 46(N-1)}, which is at most 2−(F+4)2^{-(F+4)} for N=⌊F/46⌋+3N = \lfloor F/46 \rfloor + 3. Then S∈[(t−e)/q,(t+e)/q]S \in [(t - e)/q, (t + e)/q] for the integer e=⌊q/2F+4⌋+1e = \lfloor q / 2^{F+4} \rfloor + 1, and π\pi is enclosed by dividing 42688010005 q426880 \sqrt{10005}\, q by t±et \pm e with directed rounding. The identities were checked numerically to 60 digits.

Evidence. Tests (elementary_constants_split_wbtest.mbt): the new enclosure at ww contains the old series enclosure at w+256w + 256 (an independent computation) for ww from 64 to 1024; it is no wider than the old enclosure at ww up to 2048; enclosures at ww and w+300w + 300 nest up to 20000 bits; and removing terms (a test hook) makes the containment test fail, so the tail count is checked and not just assumed. A one-off comparison against MPFR 4.2.2 (mpfr_const_pi, mpfr_const_log2, mpfr_log(10) at 2w+642w + 64 bits) at 64, 100, 257, 1000, 4096, 8192, 30000 and 100000 bits found every enclosure containing the MPFR value, one to two units of the last place wide. All binary tests pass on native, wasm, wasm-gc and js, just pr passes, and 30000 (native) and 10000 (each of wasm, wasm-gc, js) random elem cases agree with MPFR.

Measured (native, release, cold enclosure at w=p+64w = p + 64, this machine). pi 449 ms to 0.67 ms at p=8192p = 8192, 14 ms to 71 µs at 2048, 0.93 ms to 15 µs at 512; ln 2 178 ms to 1.33 ms, 5.6 ms to 156 µs, 0.36 ms to 32 µs; ln 10 (with ln 2 cached) 89 ms to 0.99 ms, 2.8 ms to 114 µs, 0.18 ms to 26 µs. At p=64p = 64 the splitting is already 3 to 19 times faster, on wasm-gc and js as well (js at 8192 bits: pi 0.63 ms, ln 2 0.67 ms), so the threshold binary_constants_split_min_precision is 64 on every target. Warm (cached) calls are unchanged. A first sin or ln at 8192 bits used to pay the series cost on top of the warm time (about 450 ms for pi, about 180 ms for ln 2); now a cold call costs at most about 7 ms more than a warm one (sin 53.4 ms cold against 53.6 ms warm, ln 101.9 ms against 94.3 ms at 8192 bits).

The cache itself is unchanged. The design asks for requests for ln 2 at a canonical precision (the next multiple of 64 above F+bits⁡(n)+2F + \operatorname{bits}(n) + 2) so that exp, ln and the trigonometric reduction share entries instead of evicting each other; that belongs to the exp kernel, which is the first caller with such an irregular precision, and is not part of the constants step.

Working-precision schedule and the Ziv loop. The attempt precisions w0=p+64w_0 = p + 64, wi+1=wi+max⁡(32,⌊wi/2⌋)w_{i+1} = w_i + \max(32, \lfloor w_i/2 \rfloor) and the budget of 12 attempts are unchanged. Each attempt picks the old or the new kernel by comparing ww with a per-target constant and, for ln and the sine, by the argument (the near-1 and tiny-argument cases above); a kernel that returns None or an enclosure wider than the old series’ falls through to the old kernel at the same ww. So an attempt never certifies less than before, and the exact cases, the tiny-argument measures, the inner-endpoint rounding and the flag argument of the loop are untouched. The result of a call is the correctly rounded value whenever either path certifies, hence identical to the current result; they can differ only in which inputs exhaust the budget, which the corpus comparison below counts. The faster attempts make a longer budget affordable, which is the point of #15: the limit is a policy of the loop and does not interact with the kernels.

Allocation and targets. BinCoeff values are immutable, so each term of a fixed-point stage allocates four arrays of up to w/32w/32 limbs (product, shift, quotient, sum); on native these are included in the measured unit costs above (shift 0.2 µs, one-limb division 1.5 µs, addition 0.3 µs at 8192 bits). The ln series loop already runs on limb arrays on the non-JavaScript targets (see “The ln series loop on limb arrays”). A fused in-place multiply-shift-divide loop on a mutable limb array for the other stages, which still allocate per term, would remove most of that for the non-JavaScript targets, and is a later optimization behind the same function, not part of the design. On JavaScript BinCoeff is a bigint: products, shifts and divisions are the engine’s, with a larger constant per operation and an asymptotically faster product, so the stage boundaries and every threshold are measured separately on native, LLVM, Wasm, Wasm-GC and JavaScript and kept next to the coefficient-kernel thresholds. The source of the kernels is shared; only the constants differ.

Evidence the new path must produce. Each kernel carries its own invariant tests: containment of the enclosure of the old path at w+256w + 256 bits in the new enclosure at ww (an independent computation), the width bound, and boundary cases (arguments at chunk boundaries, RR near 00 and 11, the corrections of nn, huge ∣n∣|n|, tiny and near-1 arguments). The end-to-end check compares every result bit for bit with the old path and with MPFR on a seeded random corpus plus the existing boundary corpus on all four targets, and a deliberately biased kernel (one unit too narrow) must make the tests fail.

Limits of the speed-up. The model reaches algorithmic parity with MPFR (exp at 8192 bits is about 65 to 100 products in MPFR and, projected, about 50 to 80 here), so the remaining gap is the product kernel: 43 µs against 3.2 µs at 8192 bits, a factor 13 (4 µs against 0.31 µs, a factor 12, at 2048 bits). Ratios to MPFR at 8192 bits in the same run (MPFR: exp 326 µs, ln 177 µs, sin 291 µs): today 55, 930 and 220; projected from this design about 6 to 11 for exp, 17 to 34 for ln and 14 to 21 for sin. A ratio below 10 at 8192 bits is therefore within reach for exp only if the product kernel also improves.

Measured result. On main 8badc55 (all four kernels merged), Apple M4, native, release, load average 1.3 to 3, three runs of just bench external quick --ops exp ln sin --binary-precisions 2048 8192 agreeing within 1 to 10 %, and a second check on 952600f within 3 %: floating time over the stored MPFR median is 6.0 to 6.6 (exp), 12.5 (ln) and 12.2 (sin) at 2048 bits, and 3.2 (exp), 10.6 (ln) and 5.8 (sin) at 8192 bits. The MPFR time measured on the same machine at the same moment was within 6 % of the stored one, so raw and drift-corrected ratios differ by at most 6 %. Three cells are below 10 times MPFR (exp at 2048 and 8192 bits, sin at 8192 bits); ln at 2048 and 8192 bits and sin at 2048 bits are above it. This is one machine and the native target only: the Wasm, Wasm-GC and JavaScript targets were not compared with MPFR. The projections above are superseded by these numbers; the remaining gap is the multiplication and division kernel and allocation, not the algorithm.

Evidence checked and still to confirm. The references were checked against the sources on 2026-11-19. Brent, J. ACM 23(2), 1976, 242-251, exists as cited, but it contains the AGM and ascending Landen transformation methods with cost O(M(n)log⁡n)O(M(n)\log n) (the logarithm by Landen transformations of incomplete elliptic integrals); it contains neither bit-burst nor theta functions, nor the nome, and it credits the O(M(n)log⁡2n)O(M(n)\log^2 n) bound to Brent, “The complexity of multiple-precision arithmetic” (Proc. Seminar on Complexity of Computational Problem Solving, 1975, pp. 126-165), which was not read. So the footnote below supports the AGM logarithm only, and the bit-burst attribution is to be replaced by that 1975 paper (not yet read). The formula with the theta functions, ln⁡(1/q)=π/AGM(θ22(q),θ32(q))\ln(1/q) = \pi / \mathrm{AGM}(\theta_2^2(q), \theta_3^2(q)), is attributed to Sasaki and Kanada, J. Inf. Process. 5(4), 1982, 247-250, on the authority of later notes by Brent (secondary sources); its normalization of the nome (Brent’s notes use q4q^4 and point out a typo in the qq form of the Borwein book) and its truncation bound have not been checked against the original, which the owner will obtain. Nothing in the design or in the code depends on the theta-function formula; the ln enclosure by the AGM depends on the model bound F(1−4/s2)≤ln⁡s≤FF (1 - 4/s^2) \le \ln s \le F only (see “ln, by the arithmetic-geometric mean” above), which follows from DLMF 19.8.5 and 19.9.2. The 1-ulp and 2-ulp widths quoted above come from the MPFR comparison, which is secondary evidence for the enclosures; the proof is the integer-bound argument in this section.

The coefficient kernel

Problem. Precision costs integer multiplication and division of pp-bit numbers, and pp ranges from 1 to 2282^{28}.

Choice. The kernel is the internal package internal/binary_kernel; BinCoeff is a newtype over its Coeff. Coeff stores up to 128 bits inline and larger values as little-endian 64-bit limbs (a host bigint on JavaScript), and dispatches on the operand length nn in 64-bit limbs. Every threshold below is in 64-bit limbs:

Product or squareNative, LLVMWasm, Wasm-GC
schoolbook product below3232
Karatsuba product from3232
Karatsuba product on 32-bit limbs fromnever160
Karatsuba square from36off
square on 32-bit limbs fromnever80
Toom-3 product from (balanced, where the NTT does not fit)40962048
two-prime NTT product from40962048
NTT square from35841536

The Native, LLVM column lists the values of the portable loops, which LLVM uses (unmeasured there). Native with the C rows has the Karatsuba square from 64 limbs, and with the assembly rows (arm64 Apple, where they are the default) the schoolbook product below and the Karatsuba product from 48 limbs and the Karatsuba square from 96. A product with m>2nm > 2n limbs is cut inside the Karatsuba into nn-limb blocks; a short operand against a long one beyond the NTT cutoff uses the NTT overlap-add. Squaring is a word-range Karatsuba square (three half-size squares a02a_0^2, a12a_1^2 and (a0−a1)2(a_0 - a_1)^2 instead of three products) on Native and LLVM, and the NTT square above its cutoff; Wasm keeps the 32-bit-limb route from 80 limbs, where a 64-bit product costs four i64.mul.

Operands with at least 4 limbs of which at most one eighth are nonzero use a sparse product of the nonzero limbs. Division uses a loop over half-limbs for a divisor below 2322^{32}, Knuth’s algorithm D on 64-bit digits (32-bit digits on Wasm) below 96 divisor limbs, Burnikel–Ziegler recursion from 96 with leaves of up to 64 limbs, and never the Newton reciprocal (the routine stays for tests); GCD switches from the binary (Stein) algorithm to Lehmer batches above two limbs. The thresholds are measured, per target, by the benchmark suite; they are policy, not semantics. The 32-bit view of the storage exists only for the Wasm routes above.

A Lehmer round is valid only when its single-word digits come from the same bit window of both operands: digits taken from each operand’s own top limb have unrelated scales, and the cofactors they produce subtract only a small multiple of the smaller operand per round. Each round therefore keeps a≥ba \ge b, runs Euclid on the leading 63 bits of aa and the bits of bb in the same window, and takes one division step a mod ba \bmod b instead when bb has no bits in that window (then a/b≥262a / b \ge 2^{62}) or when the cofactor matrix would make an operand negative or shrink neither. Every matrix applied has determinant ±1\pm 1, so the gcd is unchanged, and a long aa is reduced modulo a short bb in one step however different their lengths are; below eight limbs of bb the loop finishes with plain Euclid.

Why exactness is preserved. Schoolbook, Karatsuba and Toom-3 evaluate integer polynomial identities, for example

(a1B+a0)(b1B+b0)=a1b1B2+[(a1+a0)(b1+b0)−a1b1−a0b0]B+a0b0,(a_1 B + a_0)(b_1 B + b_0) = a_1 b_1 B^2 + \bigl[(a_1 + a_0)(b_1 + b_0) - a_1 b_1 - a_0 b_0\bigr] B + a_0 b_0,

and Toom-3 (evaluation at 0,1,−1,2,∞0, 1, -1, 2, \infty) interpolates with exact divisions by 2 and 3 of signed intermediates known to be multiples, so they are exact integer computations. The NTT is the only modular step. It splits each operand into 16-bit digits, so each coefficient of the digit convolution is at most

min⁡(na,nb) (216−1)2<223⋅232=255\min(n_a, n_b)\,(2^{16} - 1)^2 < 2^{23} \cdot 2^{32} = 2^{55}

for transform lengths up to 2232^{23}. It computes the convolution modulo the primes p1=998244353=119⋅223+1p_1 = 998244353 = 119 \cdot 2^{23} + 1 and p2=754974721=45⋅224+1p_2 = 754974721 = 45 \cdot 2^{24} + 1, both of which have 2232^{23}-th roots of unity, and recombines by the Chinese remainder theorem, which is unique in [0,p1p2)[0, p_1 p_2) with p1p2≈259.4>255p_1 p_2 \approx 2^{59.4} > 2^{55}. So the recombined coefficients are the exact integers. The length check precedes every transform; a longer product uses overlapping blocks of admissible length or falls back to Toom-3. Division paths return (q,r)(q, r) with n=qd+rn = qd + r and 0≤r<d0 \le r < d by construction; the Newton path corrects its approximate quotient with the remainder and aborts if more than two corrections would be needed, which would indicate a bug rather than a numerical event. Because all paths compute the same integers, the choice of algorithm cannot change any rounded result, flag or encoding.

Ordering NaN in compare

Problem. MoonBit’s Compare trait asks for a three-way comparison that sorting and ordered maps can rely on. IEEE comparison is a partial order: NaN is unordered with everything, itself included.

Options. (1) Abort on NaN, as earlier versions did; every sort of data that might contain a NaN then becomes a crash. (2) Use IEEE totalOrder, which is total but distinguishes −0<+0-0 < +0 and puts negative NaNs below −∞-\infty, so compare would disagree with numerical equality on zeros. (3) Keep the numerical order on numbers and put all NaNs in one class above it.

Choice. Option (3). Define the key κ(x)=(0,x)\kappa(x) = (0, x) for a number and κ(NaN)=(1,0)\kappa(\mathrm{NaN}) = (1, 0), ordered lexicographically; compare(x, y) is the comparison of κ(x)\kappa(x) and κ(y)\kappa(y), with −0-0 and +0+0 mapped to the same number. A comparison of keys in a totally ordered set is reflexive, transitive and total, so compare is a total preorder; it is not antisymmetric (−0-0 and +0+0, or two NaNs with different payloads, compare equal but are different values), which Compare does not require. The cost is that nan > 1 is true under <, so code that needs IEEE semantics must use compare_checked (error on NaN), compare_quiet / compare_signaling (four-valued, with flags) or total_order. Structural == stays the derived Eq, because it is the only equality that is a congruence for every method (precision and payload included).

Correctness and invariants

  • Canonical form. Every finite value produced by the API has cc odd or c=0,e=0c = 0, e = 0, and bits⁡(c)≤\operatorname{bits}(c) \le its precision; stored exponents never saturate (a saturated exponent is classified as overflow or underflow first).
  • Correct rounding. For every arithmetic operation, conversion and elementary function and every context, the returned finite value equals ∘(r)\circ(r) for the exact real result rr, with the range rules above. By (R1), ∘(r)=r\circ(r) = r and no flag is raised whenever r∈Fr \in F; apply_ctx is idempotent.
  • Flags. inexact iff ∘(r)≠r\circ(r) \ne r; overflow implies inexact; underflow iff tiny (per the context rule) and inexact; division_by_zero only for an exact infinite result of finite operands; invalid_operation iff a quiet NaN was produced from non-NaN operands or a signaling NaN was consumed. Exceptions to the last rule: min, max, pow⁡(x,±0)\operatorname{pow}(x, \pm 0), pown⁡(x,0)\operatorname{pown}(x, 0) and pow⁡(1,y)\operatorname{pow}(1, y) accept a signaling NaN without the flag. combine is associative, commutative and idempotent.
  • Error model. Consequently, in the normal range, ∣∘(r)−r∣≤u∣r∣|\circ(r) - r| \le u|r| for nearest and <2u∣r∣< 2u|r| for directed rounding, with the absolute term η/2\eta/2 (respectively η\eta) below 2emin⁡2^{e_{\min}}, and subnormal sums and differences are exact.
  • Monotonicity. Each operation is monotone in each argument where the real function is, because it is ∘∘f\circ \circ f with ∘\circ monotone; in particular RD and RU results bracket the exact value, which interval and the directed square roots of sqrt_ctx rely on.
  • Exactness theorems. remainder, scaleb in the normal range, copy_sign, neg, abs, logb and decoding are exact; the integral roundings never need a second rounding; fma(a, b, -RN(ab)) is exact without underflow.
  • Complexity. Addition is linear in the operand length (and independent of the exponent gap, by the far-operand rule); multiplication follows the kernel table, O(n2)O(n^2) to O(nlog⁡n)O(n \log n); division and square root cost a constant number of multiplications of the same size at large nn; remainder costs O(log⁡(qx−qy))O(\log(q_x - q_y)) modular multiplications; an elementary function evaluates its series at the working precision ww, and because ww grows geometrically the total cost of all attempts is within a constant factor of the last one.

The longer proofs (the far-operand addition rule, nextUp, the remainder reduction, the Ziv acceptance test and the NTT bound) are collected in the attachment.

Rounding and exactness proofs for the binary package

Alternatives rejected

  • Host Double for anything but from_double. Routing binary16, binary32 or binary128 through Double double-rounds, loses signaling NaNs on some targets and cannot represent binary128 at all. Interchange encoding is done on BinCoeff bit patterns instead.
  • A fixed number of guard bits. Three guard bits suffice for addition of two pp-bit operands, but not for division, square root, conversions from decimal or operands wider than the context. Deciding from exact integer data (round, sticky, remainder sign, midpoint comparison) works for all of them with one finalizer.
  • Rounding to pp bits, then to the subnormal grid. This double rounding produces wrong subnormal results; the finalizer shifts once to the coarser of the two positions.
  • Ziv with an estimated error bound. It requires a separate error analysis for every function and every reduction, and a mistake in it silently returns a wrong last bit. Outward-rounded enclosures make the bound a computed quantity, at the cost of evaluating every operation twice.
  • Global flags and rounding state. IEEE 754 describes flags as sticky global state. A returned BinaryFlags value composes with pure code, concurrent code and the Result style of @lf_arith, and combine recovers the sticky behaviour where wanted.
  • compare aborting on NaN, or compare as totalOrder. See Ordering NaN in compare.

Boundaries

binary deliberately does not:

  • provide interval or ball arithmetic: enclosures are internal to the certification loops; interval builds inf-sup interval arithmetic (a lower bound and an upper bound) on top of Binary;
  • implement IEEE 754 alternate exception handling (traps, substitution) or sticky global flags: flags are returned values;
  • implement decimal floating-point (decimal, decimal_gda) or the non-binary IEEE operations on them;
  • promise any NaN payload for a newly generated NaN (it uses payload 0), or propagate payloads of more than one input;
  • guarantee completion of an elementary function within any time for every input: certification has a budget, and an exhausted budget is reported, not hidden;
  • expose limb layout, thresholds or transform parameters: they may change without notice as long as every result, flag and encoding stays the same;
  • claim conformance beyond the finite corpus recorded in conformance.

Footnotes

  1. IEEE Std 754-2019, IEEE Standard for Floating-Point Arithmetic: clause 3 (formats), 4.3 (rounding-direction attributes), 5 (operations), 6 (infinities, NaNs, signed zero), 7 (default exception handling). ↩

  2. N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM 2002, §2.2; D. Goldberg, “What every computer scientist should know about floating-point arithmetic”, ACM Computing Surveys 23(1), 1991. ↩

  3. J.-M. Muller et al., Handbook of Floating-Point Arithmetic, 2nd ed., Birkhäuser 2018, §2.1 and §4.3. ↩

  4. Muller et al., Handbook of Floating-Point Arithmetic, §5.3 and §7.6. ↩

  5. T. J. Dekker, “A floating-point technique for extending the available precision”, Numerische Mathematik 18, 1971; Muller et al., §4.4. ↩

  6. The digit count ⌈plog⁡102⌉+1\lceil p \log_{10} 2 \rceil + 1 suffices for round trip (Matula 1968; Goldberg 1991, Theorem 15); the extra digit is a margin for the bisection’s upper end. ↩

  7. A. Ziv, “Fast evaluation of elementary mathematical functions with correctly rounded last bit”, ACM TOMS 17(3), 1991; for interval evaluation see W. Tucker, Validated Numerics, Princeton 2011, and F. Johansson, “Arb: efficient arbitrary-precision midpoint-radius interval arithmetic”, IEEE Trans. Computers 66(8), 2017. ↩

  8. I. Niven, Irrational Numbers, 1956, Corollary 3.12: if rr is rational and sin⁡(πr)\sin(\pi r) is rational, then sin⁡(πr)∈{0,±12,±1}\sin(\pi r) \in \{0, \pm\frac12, \pm 1\}; similarly for cos⁡\cos, and tan⁡(πr)∈{0,±1}\tan(\pi r) \in \{0, \pm 1\}. The value ±12\pm\frac12 needs rr with denominator 6 or 3, which is not dyadic. ↩

  9. R. P. Brent, “Fast multiple-precision evaluation of elementary functions”, J. ACM 23(2), 1976 (bit-burst and the AGM logarithm; citation to be confirmed against the paper). The truncation bound of the AGM kernel is taken from DLMF 19.8.5 and 19.9.2 (see “ln, by the arithmetic-geometric mean”), not from this paper. MPFR’s log.c documents the same algorithm and is secondary evidence only. ↩