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, for the exact real
, together with exactly the IEEE status flags, for every precision
from 1 to bits and every exponent range up to . 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
where is a BinCoeff and is exponent2(). The representation is
canonical: if then is odd, and if then . Every
dyadic rational has exactly one such form (factor out
), 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
and every comparison, range check and rounding decision below is phrased in terms of and instead of floating logarithms. Each value also carries a precision with ; 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:
| constructor | holds | when |
|---|---|---|
Fin64 | sign, one word, , | ; zero is word = 0, |
Fin128 | sign, two words, , | |
FinBig | sign, a Coeff, , | |
Inf | sign, | |
NaN | sign, signaling bit, payload, | a 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 bits has a sign bit, a -bit biased exponent field and a -bit trailing significand field (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 , the bias and , an encoding means
| Format | largest | smallest normal | smallest subnormal | |||||
|---|---|---|---|---|---|---|---|---|
| binary16 | 16 | 5 | 11 | 15 | −14 | |||
| binary32 | 32 | 8 | 24 | 127 | −126 | |||
| binary64 | 64 | 11 | 53 | 1023 | −1022 | |||
| binary128 | 128 | 15 | 113 | 16383 | −16382 |
Forgetting the encoding, the finite values of the format are
A BinaryContext is exactly this triple plus a rounding direction and a
tininess rule. Its and are leading-bit exponents, so a
normal number has , and the
grid below has the fixed quantum
the smallest positive subnormal. Missing bounds are replaced by the
implementation range , which is large enough that every
exponent arithmetic step fits a 64-bit intermediate and every stored exponent
an Int; binary_precision_max keeps in range
too.
Rounding functions
For let and
, extending by beyond
for the moment. The six rounding directions of
BinaryRoundingMode are the maps
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 above carry most of the proofs on this page:
(R1) holds because on . (R2) holds because each is one of the two neighbours of chosen by a rule that only moves from to as increases through a cell .
The standard error model
Let be the unit roundoff. Take with , (the normal range) and below the overflow threshold of the rounding direction (otherwise the result is an infinity and no relative bound holds). The points of in that binade are spaced apart, and belongs to or is the overflow point, so
where RN is RNE or RNA. Writing gives the standard model
The nearest bound sharpens to by dividing by instead of .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 the spacing is the constant , so the error is absolute: and . Both regimes together give the model with an underflow term,
for nearest rounding ( and for directed rounding). Addition and subtraction never need : if then both are integer multiples of , so is , and a multiple of below lies in . Hence a subnormal sum is exact, which is why gradual underflow keeps .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 , not merely some point within . 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 for the exact real , but may need far more bits than (a product of two -bit numbers has ), or infinitely many (a quotient, a square root, ).
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 and calls
one finalizer. For dyadic results (sum, difference, product, fma,
scaleb, remainder, conversion) the description is the exact integer
magnitude and exponent with . The finalizer picks the
shift
the larger of the precision shift and the shift onto the subnormal grid, and splits with and into three items of data:
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 the last bit of ,
| Direction | increment when |
|---|---|
| RNE | |
| RNA | |
| RZ | never |
| RU | |
| RD | |
| RA |
Derivation. , , and . RNE rounds the magnitude up when , or when and is odd; that is . The directed rows round the magnitude up exactly when and the direction points away from zero for the sign . Inexactness is .
Why. Because already includes the subnormal shift, a tiny result is rounded once, directly from , to the grid . Rounding first to 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 (when ) only raises 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 and (the context range, clamped to the implementation range), then is representable: , so the shift is , 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 , 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 bits (a carry out of gives a power of two, which is even and is stripped to ), its top bit is at least and at most (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 (little-endian, the top limbs may be zero), the exponent of bit 0, the precision, a sticky flag and the rounding direction. With and , 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 of the lowest set bit of the rounded value without forming it. Let be the kept bits.
- No increment: is the position of the lowest set bit of at or above , and the coefficient is .
- Increment: has as many trailing zeros as has trailing ones, say , and because bit of is zero. So is the position of the lowest zero bit of at or above (at most , since bit is zero) and the coefficient is ; when every kept bit is set, and the coefficient is , which is stripped. No carry is ever propagated.
The coefficient is then 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 plus an amount in units of bit 0”. It is allowed only when , and then it changes the decision only through , because the discarded part with integer and is below, at or above the half exactly as is, except that is above it. This is what lets a caller truncate a quotient, a square root or an aligned sum at 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. with , is a rational (, , ) whose binary expansion is usually infinite.
Choice. First the exact leading exponent: with , is if and otherwise, one integer comparison. That fixes the target exponent , and then one integer division
gives directly, and the remainder gives the rounding data: , so
No approximation of is involved; the rounding is decided by the sign of . When the shift is moved to the denominator, and a quotient below one unit is decided by comparing with without forming it.
Square root from an integer root and a midpoint test
Problem. is irrational unless is a square.
Choice. The leading exponent is (floor division), which fixes as above. Write the radicand as , so . An exact integer square root gives with remainder ; the root is exact iff the remainder is zero. Otherwise the rounding data come from the midpoint :
an exact comparison of integers (with the power of two moved to the other side when is fractional). So and . When 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 of a -bit number is never a -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 an exact midpoint (for example rounded to one bit).
Exponent range, overflow and underflow
Overflow is decided on the rounded value: if the rounded result has , the operation overflows, which is IEEE 754’s “after rounding” rule (clause 7.4). From the rounding table this happens at the thresholds
because a value in rounds to
nearest down to , while the tie
goes to the even neighbour , which lies outside . An
overflowing result is for the first two groups and for
the third, always with overflow and inexact. In binary16,
and :
///|
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
. IEEE 754-2019 (clause 7.5) allows two readings, and
TininessDetection selects one:
where rounds to bits with an unbounded exponent range. The finalizer computes 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 just below that rounds up to it at bits: for binary16, is tiny before rounding but rounds at 11 bits to , 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
shows the full rule: the exact value
is tiny under both readings, lies halfway between two
subnormals of spacing , rounds to the even neighbour , 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 in
magnitude (decided from exponent bounds without forming it, for example
) rounds to or 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 ( for exp2 of an integer, the
exact power of pow with a dyadic result) passes it to the finalizer as the
pair . It does not build a Binary first: a Binary made from
at one bit has its smallest value at , so with
was flushed to zero before any context could round it, although
it is exactly representable at . The after-rounding rule uses
with no exponent range at all, not an unbounded context,
which still has gradual underflow at the implementation limit
.
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 from certified bounds of
(binary_positive_exp_minus_one_overflow, including the window
and, for base 2,
with );
and one Ziv driver (binary_ziv_round). For an integer with
the value lies in the open interval between the midpoint under
and , 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 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. is
rootn(x, -2), for is pow, and is pown of the
exact sum whenever that sum fits in bits. The one decision
of its own is the tiny rule of compound: for the exact
value is with , far inside the window
around bounded by the breakpoints and , so the
result is or its neighbour by direction alone and equals the rounding of
the surrogate , 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
, ,
and : the existing
certified enclosures of the angle divided by a certified enclosure of ,
rounded by the Ziv driver. By Niven’s theorem the only exact (dyadic) values are
the constants of §9.2.1 and ,
, which are rounded as
dyadics; , and 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: with for , ;
with for a tiny
; and at () and
(, ), where is the difference of the leading-bit
exponents, so that the ratio (whose exponent can be ) is never
formed. For and a ratio so small that lies below a quarter of the
smallest subnormal the result is the tiny nonzero result of the direction.
Everything else is the enclosure (or
) 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 flushes every value below
, 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):
| name | use |
|---|---|
binary_nan_unary(value, context) | NaN operand: quiet NaN, invalid for a signaling one; call first |
binary_pole_result(negative, context) | with divideByZero |
binary_integer_result(n, context) | an integer result rounded as a dyadic |
binary_pow2_minus_one_integer(n, context) | for any integer |
binary_saturated_minus_one(context) | decided by direction |
binary_positive_exp_minus_one_overflow(...) | certain overflow of from certified |
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 -bit rounding with no range (for after-rounding tininess) |
binary_tiny_argument_result(anchor, above, scale, context) | a result within 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 ), 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 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 by MPFR’s own
convention where §9.2.1 says (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 with of opposite sign is in every
direction except RD, where it is ; (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
(, , , ,
, ,
). 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 but , has the sign of , and and are negative exactly for an odd integral .
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 is
normal when , that is when the exponent of its leading
bit is at least , and subnormal otherwise. A Binary stores no
(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 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 has payload bits, so every operation
and constructor that delivers a NaN at another precision truncates, 6.2.3), and
a format holds 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. is exact as a dyadic number, but forming it needs a two-billion-bit coefficient.
Choice. When the leading exponents differ by more than , the sum is formed on the grid with unit , where is the exponent of the last bit of the larger operand, so . The larger operand is exact on that grid; of the smaller operand only the integer part of its value in units enters, and if anything below was discarded the magnitude becomes (for subtraction ) in units of , that is, one sticky bit at the half unit.
Why it is exact for rounding. The result has , because the smaller operand is below . The last retained bit of the rounded result therefore has position at least (more on the subnormal grid), and its round bit at least . The true sum and the substitute both lie strictly inside the same open interval (or are equal when nothing was discarded), and that interval lies between two consecutive multiples of , at least two bit positions below the round bit. So and agree, and is set in both cases exactly when something nonzero was discarded. The argument does not need the larger operand to have at most bits. For subtraction, with , 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 bits.
Choice. Let be the operand with the larger top bit and the other, the exponents of their lowest bits, and . The sum is formed in a window of limbs whose bit 0 has weight , with
So , 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 once. is never cut (). When reaches below the window, its dropped part is non-zero, because stored coefficients are odd (bit 0 of is dropped), and that is the sticky flag; when lies entirely below, none of its limbs is read. For a subtraction with a cut operand the loop starts with a borrow of one: with the integer part and , 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 is cut, then , so its top is below and the gap between the tops is at least . Then for an addition has at least bits, and for a subtraction , so has at least bits. By the argument of the finisher (the discarded part is with integer and ), bits and the sticky flag decide every rounding direction. If is not cut the result is exact. When the tops differ by at most one, the exact difference fits the window (), and any number of leading limbs may cancel: the finisher scans down to the top limb. For equal tops the difference is formed as 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 exactly as a value whose
precision equals its own bit length, and passes it to the addition finalizer,
so is rounded once (clause 5.4.1). The difference from two
roundings is the point of the operation: for in
binary64, the rounding error 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,
. That the result is exact is Dekker’s theorem:
the error of a rounded-to-nearest product is itself in when no underflow
occurs (precisely, when for the exponents of
the last bits of and , so the exact product lies on the grid of
).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 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 (same precision , same range) and , then with lies in .
Proof. Write , with and . By the choice of , . If then . Otherwise , so . Now is an integer multiple of .
- If : with , so .
- If : with , so .
In both cases , the exponent is at least , and , so .
The implementation never forms , which can have bits. With , , (integers), it computes by modular exponentiation of when . Writing , , gives , so alone yields both and the parity of , which is all the ties-to-even choice of needs. The exact 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 to and rounds toward
, where .
Every gap between consecutive points of next to is at least
and itself is a
multiple of , so for , and
by the definition of RU the result is the least point of above . The
same argument works for an with more than 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 to
.
scaleb_ctx(x, n) (with n an integer-valued Binary) is the finalizer applied to : exact in the
normal range, correctly rounded with underflow and overflow outside it.
logb_ctx returns , which is exact and correct for
subnormal because is computed on the integer
coefficient. The integral roundings use the same round and sticky bits with
(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 exactly ( an integer
without trailing zeros). For up to
( the number of
digits) it is rounded exactly: by the dyadic
finalizer for , and by the division
finalizer for . Beyond that bound it uses directed enclosures
at a working precision , 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 (directed modes) or the
midpoints between them (nearest modes); both are dyadic with at most
significant bits. For the odd part of is a multiple of
, and beyond the bound, so the value
is no breakpoint: . For
, gives , so and
is not even dyadic. The points where a flag changes (the
overflow threshold, for tininess, the points of for
inexactness) are dyadic with at most 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 , eventually lies strictly
between two of them, so some certifies it; with no count limit
(BinaryContext::with_refinement_limit(None)) the loop ends by itself once
passes the work cap below. Values whose
binary logarithm is certainly beyond the range, estimated with
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 or below ( 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
with . starts from ,
which is within one of the answer, and is corrected by comparing with
, 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 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
() increments and repeats.
Shortest output. Let be the set of reals that round to under RNE in the context; it is an interval containing . For each digit count , the two -digit decimals next to (truncated and rounded away from zero) are candidates, and a candidate is accepted when parsing it returns , that is when it lies in . Acceptance is monotone in : if the -digit truncation lies in , the -digit truncation satisfies (in magnitude), so it lies in the interval too, and likewise for the upper neighbour. So the least accepted is found by bisection on , an upper bound at which a candidate is always accepted.66 The digit count 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 the value 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 in which every internal operation is rounded downward for and upward for at a working precision . If
the common value is returned, otherwise grows. The value is sound by (R2): implies , so equal ends force .
The flags need a separate argument. Overflow and tininess (under either rule)
depend only on through a threshold, so on one side of zero they are
monotone: if and (which have the same sign once they round to the
same nonzero value) agree, every agrees with them.
Inexactness is not monotone: it is false exactly on . If round to
the same value with inexact, then is inexact unless
. The loop cannot tell these apart, so the flags are right
only if every input whose exact result lies in 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 and round to different
neighbours of ).
The enclosures come from series with rigorous tails and from monotone reductions. For on , the terms satisfy , so after the last summed term
and the code stops once and adds (rounded upward) to the upper sum; the lower sum of positive terms is already a lower bound. Larger arguments are halved times and the result squared times, which is monotone on positive numbers and therefore keeps the enclosure; handles negative arguments. For with the series is
with tail , the bound the code adds. The trigonometric functions
reduce by an enclosure of (the cached binary-splitting , see
“Where comes from” below) at
bits, so the quadrant
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 ; its cost grows with , so inputs needing more than
8,000,000 bits are refused with ResourceLimit rather than run for minutes.
Budget. The loop starts at (for some functions at the
operand precision plus 16 when that is larger) and steps
, at most attempts, where
is the refinement limit of the context (BinaryContext::refinement_limit,
default ; a value below counts as ). For binary64 and the
sequence is 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 certifies it.
With = None the count is unbounded, but the loop is not: it stops, with
the same CertificationFailure, when exceeds
bits (capped at so fits Int32),
and a trigonometric argument that needs more than bits for its
reduction is still refused with ResourceLimit whatever the limit. So None
cannot allocate without bound: each step costs for the working
precision the cap, and the number of steps is at most
. A result that sits at distance
from a breakpoint needs , so the default
decides everything farther than about from a breakpoint
at binary64 and None extends that to the cap. Functions without a context
argument (the Interval enclosures) keep . 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, must not be a
breakpoint of (a point of , a midpoint, or a flag threshold), all
of which are dyadic. For a nonzero dyadic , , , ,
, the hyperbolic functions, their inverses and ()
are transcendental by Lindemann–Weierstrass. For , ,
and irrationality is enough and elementary: with
is irrational, so is dyadic only for integral , and
forces , a power of two; likewise and
are dyadic only at integral and at . For
the -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 is
rational and is rational, then
; similarly for , and
. The value needs 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: , , , for integral
, , the -scaled cases, for
integral (beyond that the odd part has more
than bits, so is not a breakpoint), for every
, dyadic powers and exact roots, and so on.
Second, the enclosure must shrink onto fast enough. The series stop
when the next term is below or in absolute
value, which is fine for arguments of moderate size; the width then is
relative to , a non-breakpoint has a positive distance to
every breakpoint, and some certifies it. Tiny arguments need the two
measures under Tiny arguments below. How large must be is the
table maker’s dilemma: no useful a priori bound is known for arbitrary ,
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 , 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 goes to
pown. A larger integral needs no filter: for with
odd, has more than bits, and a power of two
lies outside every exponent range, so neither is a breakpoint. Every
other exponent is with odd and . If is
rational, so is , and ; comparing the
exponents of and of each odd prime gives with odd,
and . Since is odd,
and every prime exponent of is divisible by , so
and . Conversely these values are
exact. So a rational pow result exists exactly under these two divisibility
conditions; for it is the dyadic , and for it is ,
which is dyadic only when . Every other pow result is irrational.
binary_pow_exact_dyadic computes the dyadic results and rounds them once,
unless the odd part would need more than bits (then it has
more than significant bits and is not a breakpoint). The same argument
with in place of shows that is
rational exactly when and ; rootn returns
rounded once for , and for the correctly
rounded quotient , 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 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 started just above the root, which
decrease monotonically to ; one power then
decides exactness. A coefficient with at most bits other than is
rejected at once, because gives .
A negative base with an integral exponent beyond the pown range is
evaluated as . Negation is an exact symmetry of that swaps
the two directed modes, , so
for an odd the code rounds with RD and RU exchanged and negates.
Tiny arguments. For small enough (about for the odd
functions, for ) the result lies closer to a representable
number than the target spacing: for the odd functions, for
, , . An enclosure whose series stops after its first term then
has itself as one end ( for , for ), and that
end rounds without inexact while the other end rounds with it, so the
acceptance test alone would only pass once separates from , at
or more. Two measures remove the dependence on .
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 that could be a
breakpoint (an odd coefficient of at most bits) by
toward the inside of the enclosure, with
. If the leading bit of is
, breakpoints near are at least apart and the offset is
at most , so no breakpoint lies in . Since
, either lies beyond or between and , and in the
second case it shares the open cell between breakpoints with and rounds
like it. So with equal flags still forces
and its flags, and the test passes as soon as the enclosure is
narrower than the spacing, independently of . pow uses inner
endpoints whenever its exactness test (above) has shown that the result is
irrational, not dyadic, or wider than bits, so a tiny exponent with
closer to than the target spacing is certified too
( in binary128 is with inexact). The test leaves a few
cases with a power-of-two base undecided (an exponent of magnitude at least
, or a scale outside the 32-bit range); those keep the plain
acceptance test.
Tiny-argument bounds. Some enclosures (for , via
, and for , ,
, , expm1, log1p) straddle the neighbour of
until . For the series give
one-sided bounds with a known side: , ,
, , ,
, , each at
most (for , mirrored for ), and ,
, ,
, each at most . With ,
binary_tiny_argument_result uses the enclosure or
with (respectively ), raised to at
least , when ( the leading bit of
), and rounds it with inner endpoints. The condition implies
, so the bounds apply, and the enclosure is
at most a quarter of the breakpoint spacing at wide. When is a
breakpoint, both ends lie in the cell next to and the result is decided
before the loop; otherwise (an argument wider than bits) the loop runs
as usual. With both measures sin and atan of at 53 bits and
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 at a working precision above the operand precision , and
for and , so an end at
disappears after an attempt or two. pow evaluates , where
can be arbitrarily small: an exponent so small that lies closer to
than the target spacing gives an enclosure with at every
affordable . That is why pow moves such an end inward once its exactness
test has excluded a breakpoint, as described under inner endpoints; for
example in binary128 is then with inexact.
Integer powers. pown_ctx computes by an addition chain at
bits with
round-to-nearest. Each chain step multiplies two
approximations; if describes the error
structure, then and , so by
induction . The computed value is therefore
with
in Higham’s notation, which is below units in the
last place of the -bit result. The code uses the radius
units (one more factor of two for a negative
power, whose reciprocal adds further factors), builds the interval, and
accepts when both ends round alike, by the same (R2) argument. When 12
attempts (with doubled between them) do not certify, the exact power
is formed and rounded, so the result is correctly rounded in
every case. A power certainly outside the range is decided first from
certified bounds; powers of two and powers whose exact value fits
in bits are computed exactly. The Ziv path therefore only sees with
odd and more than bits, or , which is not dyadic: neither
is in , so the inexact it reports is right (the flag argument above). A
with exactly bits is a midpoint; the enclosure then never
certifies under nearest rounding and the exact fallback decides it.
hypot. hypot forms 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 ,
. Write with
leading bit and : and every rounding
breakpoint near it are multiples of , so when no breakpoint
lies in and every such gives the same rounded
result and flags. is enough, and binary_hypot_negligible_operand
then replaces by , which keeps the shift at about twice the operand
and target precisions however far apart the exponents are
( with inexact). A shift above
bits is still refused as a certification_failure; after the
replacement it needs a precision near bits.
atan, asin, acos and atan2: one evaluation chain for the pair. The
enclosure of over a pair is computed by one
chain, not by one chain per endpoint. is odd and
increasing, so and
enclose on
the whole pair. For and the reduction is
with
, which is
increasing on (it is a composition of increasing maps). Hence
for every , where divides
rounded down by an upper bound of and divides
rounded up by a lower bound of ; 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 and
), 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 is
; a pair that contains zero is widened to with
, which contains it. The old code evaluated the series once
for , twice up to 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 of the reduction leaves the exponent range
for , so for a leading bit of of at least the
reduction is formed without it: with ,
and
, hence
, evaluated with directed reciprocals
of ; the relative gap is below . An infinite end of a pair
(a quotient of atan2 that overflowed) is bounded by rounded in the
matching direction. The test atan_single_evaluation_wbtest.mbt covers
for on both sides of and near , both signs and
three rounding directions, against from the cached constant; the public
results equal those of the previous code there.
For the pair is the ratio ,
increasing on . With on the
operand pair (directed roots of directed ), the lower end is
if and if , the upper end is
if and if , which replaces the
eight directed quotients and the search for their minimum and maximum. For
and the ratio of a
rectangle with of one strict sign takes its extremes at the corners
selected by the signs of the ends of (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 ) 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 the series is evaluated as with , increasing in , so on a pair the enclosure is with and . is computed with integers of fractional bits, where : a lower chain by floors and an upper chain 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 and by a division by a single word. For terms decreasing in size the partial sum after an odd number of terms is at least and after an even number at most ; with , , and this gives (odd partial sum, upper terms added, lower terms subtracted) and (even partial sum, without the last odd term), and the loop stops at an odd whose is below two units. Every floor or ceiling loses at most one unit and , so the chain errors stay below two units, each term is within three, and the whole enclosure within units of , which the 20 and guard bits cover relative to . For the series is not run: and , so the enclosure is . 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 .
Where comes from. The binary-splitting of this package is
cached per working precision. Binary .try_atan_ctx returns the
correctly rounded from that cache, so decimal and interval obtain
from two calls (rounding
downward and upward) and a scaling by , which is exact: the same interval,
bit for bit, as , 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 from one kernel call and , the enclosure of is with directed divisions (the reciprocal is decreasing); if is not positive (an underflowed enclosure) the kernel is called on as before. and then combine the four ends as before. For with and the quotient is increasing in and, for , decreasing in (the reverse for ), so the extremes are if and otherwise (lower end), if and otherwise (upper end): two divisions instead of eight. At arguments where leaves the exponent range the enclosures are the same as before (, ) or instead of a NaN end (), and the public results did not change in the tests at those arguments.
Corners by sign. The product of two intervals is no longer the minimum and maximum of four rounded products. With nonnegative, the smallest over the box is if and otherwise (take the smallest , then the that suits its sign), and the largest is if and otherwise; a nonpositive is and a mixed with a sign-definite swaps the roles; two mixed intervals still take the four corners. The quotient by a positive interval has the lower end if and otherwise, and the upper end if and 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 (the lower bound of is half the lower bound of , exact), then at both ends, the nearest integer is for both, the product is and the reduced argument is the input itself; the division by 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 ). 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 of has two distinct ends (it comes from both bounds of ), and the enclosure of the series used to be the lower end of the series at and the upper end of the series at : two series evaluations. Sine and cosine are 1-Lipschitz (, ). Take any value (here the midpoint rounded to nearest at the working precision) and with both differences rounded upward; then every has , so and with the two sums rounded outward, where is the series enclosure at . Soundness does not need to lie in , since covers both distances whatever is. The widened enclosure is then clamped to what is known of the function: the range bounds and for both functions (and the cosine keeps its upper end when ), and, for a sine whose reduced interval has ends of one sign, the sign (the lower end is at least when , the upper end at most when ). 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 . The cosine of a tiny argument is , closer to than the work precision resolves, so the unclamped upper end lies above the breakpoint 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 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 certifies a directed rounding; the end of the first form has far more bits than a breakpoint, so that step did not apply to it. The same holds for , 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 are rounded to the quantum of the work precision (a value of width stores nothing below ); while at least 64 bits of the product lie above the quantum, 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 or below and is clamped at , 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 wherever the two-ended one did (the reduced argument is within , so the cosine is at least and is a few units of the working precision). The new enclosure contains the exact value and is at most wider on each side than the two-ended one (where the derivative is small the two-ended enclosure was narrower than the interval); 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 of a rounding boundary. The tests keep the two-ended function and check that the new enclosure lies inside the old one widened by 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 and for from 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 , in the five rounding directions at precisions , , , and , 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 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 (within the gate described below) the result is rounded in one step, without a Ziv loop. For a positive with , the top bit of is ( because are integers); the top bit of is , or when ( exactly), by the same inequality on . With the exponent of the last place of the rounded result (the subnormal grid included), take (half a unit) and the integer
(for ) or (for );
since for real (an integer has exactly when ), (the integer square root kernel for , the integer Newton root otherwise) is . The retained part is , the round bit is the low bit of , and the sticky bit is “the root is not exactly ”, which holds unless was exact (no dropped bits, no remainder) and : a boundary of any rounding direction is a multiple of half a unit, so a root strictly between and is on the same side of every boundary as 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 bits and the Newton steps of its root raise a number of that size to the power , 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 the integer root wins at every precision measured (53 to 32768 bits) by 2.4 to 300 times; for it wins by 6.7 to 49 times up to 1024 bits, but at 2048 bits gains only 1.6 times, 1.1 times, and and are 1.3 and 2.2 times slower. The gate is therefore , or 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 2.1, 3.6 and 11 times fewer.
Trigonometric functions of huge arguments
sin, cos and tan of an argument with reduce modulo
, which cancels the top bits of : the reduction needs to
bits for a result of bits. The reduced argument lies in
and the series needs only the precision of the result, so
for the enclosure of the reduced argument is rounded outward to
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
() is evaluated; a larger work size is a
ResourceLimit certification failure. The decimal driver passes a huge
integer operand to Binary exactly (an integer 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 because at bits is
computed by binary splitting with a quasi-linear product (a call recomputes
: 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):
| operation | seconds | instructions retired | peak memory |
|---|---|---|---|
| at 1,000,000 bits | 1.5 | 31.1e9 | 14.6 MB |
| at 2,000,000 bits | 4.5 | 119.6e9 | 20.3 MB |
| at 3,400,000 bits | 12.7 | 340.1e9 | 28.4 MB |
sin of 1E+300000 | 3.8 | 88.3e9 | 17.2 MB |
sin of 1E+600000 | 12.8 | 341.5e9 | 22.4 MB |
sin of 1E+999999 | 34.9 | 936.7e9 | 33.5 MB |
The series change alone, sin(2^k) with (origin/main before and after):
| before, seconds | before, instructions | after, seconds | after, instructions | |
|---|---|---|---|---|
| 50,000 | 0.40 | 10.2e9 | 0.01 | 0.19e9 |
| 100,000 | 2.05 | 53.2e9 | 0.02 | 0.62e9 |
| 200,000 | 8.82 | 232.2e9 | 0.08 | 2.19e9 |
| 400,000 | 164 (loaded machine) | not measured | 0.30 | 7.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 -bit numbers, so one evaluation costs
full multiplications, that is . At
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
-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,
. (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:
with binary splitting inside and, with the plain
fixed-point series inside, one cheap unbalanced product per term
(measured: bits 1.8 µs, bits 6.9 µs,
bits 43 µs). (3) Newton iteration for ln on top of exp.
(4) The arithmetic-geometric mean (AGM) for ln and pi,
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 for a given
, and only from a per-target precision threshold upward. Every new
kernel is a pure function 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 -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 with , 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 is carried as a
pair of integers with the invariant
. 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 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 ( with , , the terms and the stop at ) 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 as one copy pass with the shift (limb offset , bit offset , the case apart), the quotient by the odd divisor in place from the top limb, and the sum with a carry. The divisor is at most (the loop stops after 10000 terms), so the running remainder and for a half limb : 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 from 60 to 700 (so every residue of modulo 64, in particular 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 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
and , tiny and large arguments) against a table generated on
the kernels before the extraction.
- Directed conversion (
fixed_scaled_floor,fixed_scaled_exact,fixed_shift,fixed_enclosure). A fixed-point integer stands for .fixed_scaled_floorrounds toward and loses less than one unit;fixed_scaled_exactisNoneunless the scaling is exact;fixed_enclosureturns an integer pair into floats rounded outward (lower endTowardNegative, upper endTowardPositive), swapping the ends for a negative result. - 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;exptables, 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. - Term-by-term stage (
fixed_series_step,fixed_exp_series). With , and , the exact term satisfies (the deficit obeys ).fixed_exp_seriessums until a term is below and returns the sum, the last term and its index; the exact value is within above the sum. The fixedexpstage and the bit-burstexpstage use it with their own slack constants (4 and 3), and the burstsin/cosstage uses the step for the real and imaginary parts of .binary_ln_unit_fixed_boundsandbinary_sin_cos_fixed_seriesstay apart: their recurrences are in and with different divisors and different tail proofs (an artanh series with ratio , an alternating series), not the recurrence above. - Binary splitting (
SplitState,split_combine,split_combine_t). A state on is with , , the power of two of kept apart in , and (partial sum), merged as . The constants (artanh and Chudnovsky series) use , the series of uses per index from 1 (split_exp_state). All of it is exact integer arithmetic, so the partial sum is the exact rational and the error bound of a kernel is the bound of its omitted tail alone. The complex stage ofsin/cos(SplitComplexState) keeps its own type because it carries two components and rotates the right component by before the merge; it sharessplit_combine_tand the products of , and .fixed_split_termsgives the number of terms for which the omitted tail of is below two units (the proof is in its comment). - Rectangular splitting (
rect_plan,rect_powers,rect_sum,rect_inverse_factorials). For a series with nonnegative integer coefficients, , , and terms, the powers () satisfy . With , and , the sum satisfies and its deficit , in the units of the common denominator of the , obeys . The coefficient sequence is the parameter:rect_inverse_factorialsgives for (deficit below 8 units of , the constant 10 ofbinary_exp_taylor_fixed); the next kernels pass with a common multiple (the odd reciprocals of and ) or and (sine and cosine, whose alternating signs the caller splits into a positive and a negative series in with nonnegative coefficients). The block size minimizes a cost estimate (rect_block_size) and never changes a result bound;rect_factorial_termsis the term count for factorial decay. - Reduction by (
fixed_exp_reduce,fixed_exp_finish), the integer reduction and the closing units of the bit-burst and the tableexp, described in the next two sections, and the chunk schedule of the bit-burst (fixed_burst_chunks), used by theexpand thesin/coskernels.
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 with
(larger magnitudes are decided before the loop or fall back),
let , found from the cached enclosure of
at bits. Let (a dyadic lower bound with ) and , computed exactly. If or the
integer is corrected by one and recomputed. Put and . Then
for (mirrored for ), so
by the choice of , and since
The factor costs at most units at the end (because ), and no sign handling or reciprocal is needed because .
Write with the bits of at positions after the binary point, , and growing geometrically (factor about 4, first chunk about 16 bits; the constants are tuned per target). Then , , and .
Stage kernel. For let and
(the second floor
is absent for ), and let be the exact terms.
By induction (both floors round down), and the deficit
satisfies and
, hence and
for (this is the argument of the
fixed-point series already in elementary_fixed_exp.mbt, with in
place of ). Stop at the first with . For
the ratio of consecutive exact terms is at most ,
so . With ,
Then folds the stage into the running product: 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 units of relative width, so
with at most stages the final width is below
units, about units for
; guard bits therefore keep the enclosure within
relative width, which is the bound the kernel checks (the
current series gives about ). The
kernel computes the true width and returns None when it exceeds that bound.
One full product per chunk. The pair and the stage (, both in units of ) are folded as . Put and . Both are short, and the kernel guarantees it: is below (the stage bound above), and never decreases from one fold to the next (each factor since ), so is at most the final width, which the final check limits to units, one limb. Observed in 150 folds of the kernel at working precisions 2112 and 8256 bits (36 pseudo-random arguments with magnitudes from to ): at most 9 bits and at most 8 bits. Then exactly, so the upper end is formed from the product 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 and is the stage itself, , without a product.
Cost. A stage with -bit numerator at position needs terms, each a product of the shrinking term by an -bit integer, a shift and a division by a one-limb integer. For 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 with exact integers , , , . The enclosure then has no accumulated rounding: , once is large enough that (an integer comparison on bit lengths), because then the tail is at most units. A stage is estimated (not yet measured) at 8 to 14 full products independent of , a fixed-point stage with terms costs unbalanced products, so the crossover per stage is at of a few tens of terms.
The merge of the tree computes the least that the integers need. The values 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) is only read when the node is a left child, and every node of one level has for the same few (the lengths of the ranges of a level differ by at most one), so is not carried: the merge reads , with the number of indices of the left range, from a table of the powers of that makes each power once as a square or as a product of two smaller ones (about powers for terms, 28 products for the 315 and 105 terms of the first two chunks at 2048 bits, against 418 products of ). (2) The shift by 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 , is written out: , (for sin and cos the real part is and the imaginary part ), 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 ( to 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:
guard bits; chunk boundaries at (first chunk 16
bits, factor 4); a chunk is evaluated by binary splitting when its term count
(from the integer bound on , using
) is at least 40, and
by the fixed-point series otherwise; ln 2 is requested at the next multiple
of 64 above . The reduced argument comes from one Euclidean division of
by , so with no
correction loop. The kernel declines (None, and the series runs) for
or , when (the result
exponent would approach the limit of the exponent range), when has bits
below , and when the computed width exceeds 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 , 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 contains the series
enclosure at for every argument the kernel accepts in a corpus of
224 values of 60 to 2000 bits with from to , and for
arguments next to multiples of , to
and to ; it is no wider than the series enclosure at
; 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 . Two obligations are not exercised by such tests: the
slack of the fixed-point stages and the units for 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 to and next
to multiples of ) 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, bits,
: 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 -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
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 rounded up to a multiple of 64
(; multiples of 256 above 1024), so . The reduction to
and the residual factor
are those of the bit-burst kernel above (3 units below, 6 above
in units of , valid because ), 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 ; its error bound is stated there and not repeated below. Then, with
( for , up to 1024,
above),
all three parts exact multiples of , so with () and ().
Tables. Built lazily, one set per value of (at most 24 sets are kept),
each entry an integer enclosure taken from the
certified kernels already in the library (binary_exp_bounds_untabled, the
bit-burst or series path, at bits): , . 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 bits. The tables are not hard-coded.
Taylor series of . Write , (so , in the shapes above). The number of terms is the least with ; as and the ratio of consecutive terms is below , the tail satisfies : at most one unit. The sum is evaluated by the rectangular (Paterson–Stockmeyer) splitting of toolkit piece 5, with rounded up to , the integer coefficients (computed once per ) and one final division, ; the powers and the recurrence for are those defined there, with (so ).
Error of the series. The exact counterpart is , and every computed quantity is a lower bound of its exact counterpart. Let in units of . The deficit of is (). In the Horner step the error of contributes (because ), the propagated error , and the floor less than one unit. So , whence for every block. The final floor loses less than one more unit, and the tail at most one:
Assembly. With the table entries (already in units of ), and . All factors are positive, so the floor-and-add-one products are monotone enclosures; the final enclosure is then rounded outward to bits. The kernel declines (the older paths run) in the same cases as the bit-burst kernel (, , , with bits below ) and when the width exceeds of the value. The width of the enclosure is a few dozen units of (the series 10, the tables 2 each, the reduction 9, the products another factor up to 2), far below the units the check allows.
Why results are bit-identical. The kernel only supplies an enclosure of
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 bits.
Evidence. elementary_table_exp_wbtest.mbt: containment of the series
enclosure at for up to 256 arguments of to at working
precisions 53 to 1000, positive and negative; arguments equal to table nodes
, and one unit below and above them (remainder at or
just off a table boundary); multiples of up to ;
the Taylor stage on at
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, ). 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 above 2000 bits, which is why it
loses there.
ln, by verified Newton step. Write with
, so . Take any dyadic
with about bits (from the same function at half the
precision, recursively, down to the existing series). Correctness does not
depend on how good is, only the speed does. Let be the
enclosure of from the kernel above and
, (directed divisions). Since
is monotone, ,
and for one has , so
whenever (checked at run time, else None).
If the quadratic term is below
and the width is that of . Adding uses the exact
integer product of with the dyadic bounds of . For the existing artanh series has terms and stays in use. The
cost is that of one exp at plus the recursive call at about
(about 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 for
(the unit enclosure that binary_ln_bounds adds to). With
bits, so that an
argument near 1 keeps significant bits of the result, is the lower
end of the enclosure of at bits, where is
rounded to that many bits (the same function one level down, so the
recursion ends in the series below the threshold); is the exp
kernel at bits; the two divisions and the final
operations use bits with directed rounding, and the result
is rounded outward to bits. It declines (and the series runs) for
or , when , and when the width of the
result exceeds 8 units of . 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 (random, near 1 down to , near 2, 3/2, 5/4) that the
kernel accepts, the enclosure at contains the series enclosure at ;
it is no wider than the series enclosure at ; 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 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 is below the
width of the exp enclosure; its justification is the paper argument
( for ), not the tests. MPFR 4.2.2
comparison: 13,200 rows (precisions 256 to 4096, four rounding directions,
arguments with binary exponents from to , 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,
bits, random in , 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 the enclosure of is built from up to a model term, with , (so and ), .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.
- The argument. : one division rounded to nearest at bits, relative error at most , then an exact shift. is increasing in each argument and homogeneous of degree one (both maps are), so for : , and symmetrically for : the relative error of moves by at most as much.
- The iteration. , from , every product, square root and sum rounded to nearest at bits (relative error 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 and , , : the product has , the root halves the exponent of that factor and adds one rounding, the sum is bounded by and halving is exact, so , and for (MPFR’s analysis of the same iteration, with the Higham calculus, gives ; ours is looser by 2).
- Stopping. After each iteration stop when (tested on exponents; when the exponents of and differ by 2 or more the two differ by more than half of the larger, which is not below , 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. lies between and , which differ by at most , so with (the from step 1 included). The code forms with directed products.
- The model term. With the lower end uses and the upper end . Both follow from two equations of the NIST Digital Library of Mathematical Functions, for and : DLMF 19.8.5, , and DLMF 19.9.2, . Put with (so and ): by 19.8.5 and 19.9.2 reads . Hence , and since for . The same inequality gives the lower bound as a by-product. The range is , and the kernel’s with satisfies it. Numerically (exact decimal arithmetic, , ) the ratio is between 0.532 and 0.964, inside the interval that 19.9.2 predicts (the values for , that is , are also inside, though DLMF does not cover them). The code subtracts , sixteen times the term that the lemma needs, and the error margin of step 3 is more than a hundred times that term: the factor is slack, not a need, and is kept as it is.
- The constants and the result. at bits and at bits (the cached enclosures), and by directed divisions, by directed products with the integer , and the subtraction directed. Cancellation: and are about and the result about with , so about bits are lost; they are paid once in the working precision (no restart, as MPFR does). The width of the result is at most by this choice and is checked (as in the Newton step): a wider result returns
Noneand the Newton step or the series runs.
Cost. iterations of one product, one square root and one sum: at 2112 bits and 22 at 8256 bits (exact decimal AGM of , 14 at 512), about . Per call: products, square roots, 3 divisions (one for , two for ), about 5 products by short numbers, the two cached constants. In multiplication units ( 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 , the series of an argument with needs about terms: they meet at 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 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 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 step | mean | ratio |
|---|---|---|---|
| 512 | 501,445 | 509,327 | 1.016 |
| 640 | 680,378 | 566,571 | 0.833 |
| 1024 | 1,536,465 | 817,721 | 0.532 |
| 2048 | 4,096,676 | 1,798,574 | 0.439 |
| 4096 | 10,223,975 | 5,172,641 | 0.506 |
| 8192 | 27,924,307 | 17,172,621 | 0.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 , , the quadrant integer
and (exact, after
a correction of ), the true reduced argument satisfies
. Sine and cosine are 1-Lipschitz, so
and likewise for the cosine; truncating
to bits costs one more unit. The quadrant maps
to the result, as in binary_reduced_trigonometric_bounds.
For the real and imaginary parts of the series of
are the even and odd terms of the same sequence as above, with
signs , so a stage costs the same as an exp stage
and gives both and . The deficits satisfy the same bound
, and each of the two alternating series has terms that decrease in
size (), so the tail after is at most
in size and the enclosure is or . Stages are folded by rotation,
, with four products and interval
bounds on non-negative integers; all partial angles lie in , 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
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
-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
. With and
, the nearest integer to
, , comes from one Euclidean
division of integers, is exact with , and the
true reduced argument satisfies
. The working scale is
with
(declined above 64, so near a multiple of keeps significant
bits of a sine), and satisfies
, so by the Lipschitz
bound the sine and cosine of are within 2 units of those of
. 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 .
The fixed-point stage sums the even terms of the series of for the
cosine and the odd ones for the sine, with signs in each, from
the same sequence as in the exp stage (deficit below 3); each of the two
alternating series decreases in size, so each sum is within of
its value. The binary-splitting stage keeps a complex state: the leaf of an index
is (the factor ), ,
, and
, where
multiplying by 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 and radii has midpoint
and radius
, and the stages are
folded by rotation, and (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 and the signs of and
select which component is the result. It declines for ,
, when the reduced argument is smaller than , and
when the width exceeds 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 , (a tree with two signed components and five products per node), but the real series , , as a tree over the indices with , () and a signed , merged exactly as the tree of (powers of from the power table, sign from the parity of the left leaves, the signed merge of split_combine_t). The exact partial sum is and the sine is , the same rational as the imaginary part of the complex tree over indices (the test compares the two as integers).
Term count. Let be the term count of the exponential series from the integer bound of the exp stage: , which follows from with and . The bound holds for every larger count: going from to the left side grows by (since gives ) and the right side by , so . The first omitted term of the sine series has the exponent , and with this is at least , so that term is , below one unit. The series alternates and its terms decrease (, the ratio of consecutive terms is ), so the whole tail is below one unit in size; the floor of the quotient loses less than one unit; the ball (midpoint , radius 2, as for the complex stage) contains .
The cosine of the stage. The fold needs the cosine too. Every stage satisfies (the chunks are parts of the reduced argument, at most ), so without a sign question, and the root is well conditioned there ( for ), so no bits are lost near (where ) and the argument never approaches . With the sine ball in units of (clamped to and , both true for the sine of ), the function decreases in , so for every : , two exact integer square roots, no derivative bound; for the upper end is . For a split stage always ( and a split stage has ), 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 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 the end is ; 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, from to ,
both signs, and the neighbourhood of nine multiples of for four
precisions) and for both functions, the enclosure at 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 units in
every stage, 40 terms fewer in the binary-splitting stages, and taken with
200 bits fewer for an argument near . A bias below about 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
to , and neighbours of multiples of ; 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,
bits, for the sine and to 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 with rigorous bounds:
where come from the Chudnovsky series (alternating, about 46 bits per term) and .
Implementation (elementary_constants_split.mbt). The state of a series on
an index range is with , and
, combined as
; the artanh series has and
, which telescope to , and the
Chudnovsky series has ,
and the leaf . Only the
Chudnovsky 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
is exact; the only roundings are the final directed divisions and
(directed sqrt_ctx), done at bits, and the result is
rounded outward to bits.
Tail bounds. For with take terms with , (using ): the first omitted term is at most and the omitted terms are positive and shrink by at least , so they sum to less than , which is added to the upper end. For Chudnovsky the ratio of the factorial parts of consecutive terms is , the linear factor grows by at most 41.11 from to and by less than 2 after that, and , so the ratios are below and then , the terms decrease in size, alternate in sign, and the first is below . The omitted sum from index is therefore at most the size of term , below , which is at most for . Then for the integer , and is enclosed by dividing by with directed rounding. The identities were checked numerically to 60 digits.
Evidence. Tests (elementary_constants_split_wbtest.mbt): the new enclosure
at contains the old series enclosure at (an independent
computation) for from 64 to 1024; it is no wider than the old enclosure at
up to 2048; enclosures at and 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 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 , this machine).
pi 449 ms to 0.67 ms at , 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 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
) 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
, and the
budget of 12 attempts are unchanged. Each attempt picks the old or the new
kernel by comparing 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 . 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 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 bits in the new enclosure at (an independent computation), the width bound, and boundary cases (arguments at chunk boundaries, near and , the corrections of , huge , 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
(the logarithm by Landen transformations of incomplete elliptic
integrals); it contains neither bit-burst nor theta functions, nor the nome, and
it credits the 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, , 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 and point out a typo in the 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 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 -bit numbers, and ranges from 1 to .
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 in 64-bit limbs. Every threshold below is in 64-bit
limbs:
| Product or square | Native, LLVM | Wasm, Wasm-GC |
|---|---|---|
| schoolbook product below | 32 | 32 |
| Karatsuba product from | 32 | 32 |
| Karatsuba product on 32-bit limbs from | never | 160 |
| Karatsuba square from | 36 | off |
| square on 32-bit limbs from | never | 80 |
| Toom-3 product from (balanced, where the NTT does not fit) | 4096 | 2048 |
| two-prime NTT product from | 4096 | 2048 |
| NTT square from | 3584 | 1536 |
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
limbs is cut inside the Karatsuba into -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 ,
and 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 , 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 , runs Euclid on the leading 63 bits of and the bits of in the same window, and takes one division step instead when has no bits in that window (then ) or when the cofactor matrix would make an operand negative or shrink neither. Every matrix applied has determinant , so the gcd is unchanged, and a long is reduced modulo a short in one step however different their lengths are; below eight limbs of the loop finishes with plain Euclid.
Why exactness is preserved. Schoolbook, Karatsuba and Toom-3 evaluate integer polynomial identities, for example
and Toom-3 (evaluation at ) 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
for transform lengths up to . It computes the convolution modulo the primes and , both of which have -th roots of unity, and recombines by the Chinese remainder theorem, which is unique in with . 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 with and 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 and puts negative NaNs below
, 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 for a number and
, ordered lexicographically; compare(x, y)
is the comparison of and , with and 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 ( and , 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 odd or , and 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
for the exact real result , with the range rules above. By
(R1), and no flag is raised whenever ;
apply_ctxis idempotent. - Flags.
inexactiff ;overflowimpliesinexact;underflowiff tiny (per the context rule) and inexact;division_by_zeroonly for an exact infinite result of finite operands;invalid_operationiff a quiet NaN was produced from non-NaN operands or a signaling NaN was consumed. Exceptions to the last rule:min,max, , and accept a signaling NaN without the flag.combineis associative, commutative and idempotent. - Error model. Consequently, in the normal range, for nearest and for directed rounding, with the absolute term (respectively ) below , and subnormal sums and differences are exact.
- Monotonicity. Each operation is monotone in each argument where the
real function is, because it is with monotone; in
particular RD and RU results bracket the exact value, which
intervaland the directed square roots ofsqrt_ctxrely on. - Exactness theorems.
remainder,scalebin the normal range,copy_sign,neg,abs,logband 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, to ; division and square root cost a
constant number of multiplications of the same size at large ;
remaindercosts modular multiplications; an elementary function evaluates its series at the working precision , and because 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.
Alternatives rejected
- Host
Doublefor anything butfrom_double. Routing binary16, binary32 or binary128 throughDoubledouble-rounds, loses signaling NaNs on some targets and cannot represent binary128 at all. Interchange encoding is done onBinCoeffbit patterns instead. - A fixed number of guard bits. Three guard bits suffice for addition of two -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 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
BinaryFlagsvalue composes with pure code, concurrent code and theResultstyle of@lf_arith, andcombinerecovers the sticky behaviour where wanted. compareaborting on NaN, orcompareastotalOrder. See Ordering NaN incompare.
Boundaries
binary deliberately does not:
- provide interval or ball arithmetic: enclosures are internal to the
certification loops;
intervalbuilds inf-sup interval arithmetic (a lower bound and an upper bound) on top ofBinary; - 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
-
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). ↩
-
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. ↩
-
J.-M. Muller et al., Handbook of Floating-Point Arithmetic, 2nd ed., Birkhäuser 2018, §2.1 and §4.3. ↩
-
Muller et al., Handbook of Floating-Point Arithmetic, §5.3 and §7.6. ↩
-
T. J. Dekker, “A floating-point technique for extending the available precision”, Numerische Mathematik 18, 1971; Muller et al., §4.4. ↩
-
The digit count suffices for round trip (Matula 1968; Goldberg 1991, Theorem 15); the extra digit is a margin for the bisection’s upper end. ↩
-
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. ↩
-
I. Niven, Irrational Numbers, 1956, Corollary 3.12: if is rational and is rational, then ; similarly for , and . The value needs with denominator 6 or 3, which is not dyadic. ↩
-
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’slog.cdocuments the same algorithm and is secondary evidence only. ↩