decimal design
This page explains the arithmetic model of Luna-Flow/floating/decimal: what a
decimal floating-point number is, how cohorts and preferred exponents carry
information, how the interchange encodings pack digits into bits, how every
result is rounded exactly once, which error bounds follow, how the exponent
range is enforced, and how elementary functions are certified. The
decimal API specifies each function; the
decimal tutorial shows them in use.
Design goal
decimal implements the decimal arithmetic of IEEE 754-201911 IEEE Std 754-2019, Standard for Floating-Point Arithmetic, clauses
3.3–3.5 (decimal formats and encodings), 4 (attributes and rounding), 5
(operations), 7 (exceptions) and 9 (recommended operations). The General
Decimal Arithmetic specification by M. F. Cowlishaw (version 1.70) gives the
same model in an arbitrary-precision form; its terms coefficient,
adjusted exponent, Etiny and clamp are used here. for any
precision, with three properties:
- Every context operation is correctly rounded. The result is the exact mathematical result rounded once, in the selected direction, to the context’s precision and exponent range — for the basic operations and for the elementary functions alike. The current implementation misses this goal in two places (integral rounding of operands longer than digits, huge exponents in text); they are listed in known deviations.
- Nothing is lost silently. The exponent of a result (its quantum), the
sign of zero, NaN payloads and every exceptional condition are part of the
returned value or of the returned
DecimalFlags. - No hidden state. Precision, rounding, exponent range and flags are ordinary immutable values passed and returned explicitly, as everywhere in Luna-Flow.
The checked ParseChecked adapter follows IEEE 754-2019 section 4.3 and section 5.12.2: text conversion uses the supplied rounding-direction attribute and the context exponent range. parse_checked returns the converted value through Result; callers that need exception flags such as overflow use Decimal::from_string_ctx directly.
Mathematical background
Decimal floating-point numbers
A decimal floating-point format with precision and adjusted-exponent range is the set of numbers
together with and NaNs, where is the coefficient, the exponent or quantum, and
Contexts require ,
and
. A shared constructor helper validates
these bounds and computes and ; invalid
parameters return an error naming the invalid field. These are the adopted
decNumber decContext.h limits and keep context-derived exponent sums within
Int. GDA 1.70 specifies no fixed context limits and requires a balanced
range; this library does not enforce that separate balance rule.
The adjusted exponent of a non-zero is : it is the exponent of written in scientific notation . A non-zero is normal when and subnormal otherwise; the smallest positive subnormal is and the largest finite value is
DecimalContext stores the precision , (and ,
IEEE 754-2019 3.3), the rounding direction and two limits
(refinement_limit, elementary_precision_limit) that bound the elementary
functions. Every context is an IEEE format: its
exponents above are not allowed (see clamping) and
tininess is detected before rounding. The library’s own working contexts, which
are not formats, are private. The interchange formats are:
| Format | bias | exponents | |||||
|---|---|---|---|---|---|---|---|
| decimal32 | 7 | 96 | 90 | 101 | |||
| decimal64 | 16 | 384 | 369 | 398 | |||
| decimal128 | 34 | 6144 | 6111 | 6176 |
IEEE 754 fixes , so the number of exponents is ; the standard chooses so that this count is , which is exactly what two leading exponent bits taking the values and further bits can encode (see encodings). The bias that turns into a non-negative stored exponent is : for decimal64, .
Why decimal
A rational number in lowest terms has a finite expansion in base if
and only if every prime factor of divides . For the only
admissible denominators are powers of two; for they are .
So every binary floating-point number has a finite decimal expansion, but
has none in binary: the Double nearest to it is
Quantities defined in decimal — prices, rates, measurements, protocol fields — are therefore represented exactly by decimal floating point, and decimal rounding happens at the decimal places a person or a regulation specifies. The price is a larger wobble (below) and more expensive digit arithmetic.
Cohorts and quantum
The map is not injective. All representations of the same non-zero value form its cohort. If has digits and trailing zeros, the members are for , ignoring the exponent range, so the cohort has members. For example, in decimal32 (, , , ) has the seven members . A zero has a member for every exponent.
The cohort member carries information numeric equality does not: 12.30
states two decimal places, 1.2E+3 states two significant digits. IEEE 754
therefore specifies, for each operation, a preferred exponent, and an exact
result is delivered in the member whose exponent is closest to it. The
preferred exponents follow from where the exact result naturally lives:
For the sum and the product, the bracketed coefficient is an integer, so the
preferred exponent is attained whenever the exact coefficient fits in
digits: 1.20 + 3.40 = 4.60 and 1.25 × 2.50 = 3.1250. For the quotient the
exact result exists only when has a finite decimal expansion; it is
then moved toward as far as digits allow, so 2.400 / 1.2 = 2.00. An inexact normal result always uses all digits, which is the
member with the smallest exponent; an inexact subnormal result ends at
. quantize_ctx makes the exponent an explicit argument, and
normalized chooses the member with the largest exponent.
For conversion from a character sequence, IEEE 754-2019 §5.2 selects the
least possible exponent for an inexact result. Thus parsing 1.0001 at
precision 3 gives 1.00, and 99999 gives 1.00E+5, since a carry into
still leaves digits; an exact result uses the representable cohort
member closest to the preferred exponent (parsing 1.000 at precision 3 also
gives 1.00).
///|
test "design: preferred exponents" {
let ctx = @decimal.DecimalContext::decimal64()
let d = fn(s : String) { @decimal.Decimal::from_string(s).unwrap() }
inspect(d("1.20").add_ctx(d("3.40"), ctx).0, content="4.60")
inspect(d("1.25").mul_ctx(d("2.50"), ctx).0, content="3.1250")
inspect(d("2.400").div_ctx(d("1.2"), ctx).0, content="2.00")
inspect(d("0.0400").sqrt_ctx(ctx).0, content="0.20")
inspect(d("1.5").fma_ctx(d("2.0"), d("0.25"), ctx).0, content="3.25")
}
Rounding directions
Let be exact and let the target exponent be (the exponent that leaves digits, or for a tiny result). Write
Each rounding direction returns or (times ); the choice depends on , the last digit of and the sign:
The kernels implement eight algorithms. A context selects one of the five
that IEEE 754-2019 §4.3 names (public DecimalRoundingMode: RoundTowardZero
is Down, RoundTowardPositive is Ceiling, RoundTowardNegative is
Floor, RoundTiesToAway is HalfUp, RoundTiesToEven is HalfEven); Up,
HalfDown and ZeroFiveUp are working modes of the library (directed bounds of
the certified functions, the guard digit of division) that no context can
select. The table uses the kernel names.
| Mode | IEEE name | returns when () |
|---|---|---|
Down | roundTowardZero | never |
Up | — | always |
Ceiling | roundTowardPositive | |
Floor | roundTowardNegative | |
HalfUp | roundTiesToAway | |
HalfDown | — | |
HalfEven | roundTiesToEven | , or and odd |
ZeroFiveUp | — |
For a negative the same rule is applied to and the sign restored, so
Ceiling and Floor swap. Every mode is monotone:
. Monotonicity is what the
certification of elementary functions relies on.
Error model
Let be in the normal range, . Representable numbers in that decade are spaced by one unit in the last place, . Rounding to nearest is off by at most half of it, so
The bound is approached, but not attained, near the bottom of a decade: for the relative error is . Near the top, , the same absolute error is only relative. The ratio between the worst and the best relative error inside one decade is therefore
the wobble of base .22 Goldberg, “What every computer scientist should know about
floating-point arithmetic”, ACM Computing Surveys 23(1), 1991, §1.2;
Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM 2002,
§2.1–2.2. In binary the wobble is 2, so for
the same storage decimal has a slightly worse worst-case relative error:
decimal64 has , binary64 has . The directed modes have
. The machine epsilon, the distance from 1 to the
next larger number, is — epsilon_contextual returns it and
next_up_ctx(1) in decimal64 is 1.000000000000001. Below 1 the spacing is ten
times smaller: next_down_ctx(1) is 0.9999999999999999.
For a subnormal result the spacing is the fixed , so
the error bound becomes absolute, . Because every context operation is correctly rounded,
the standard model ,
, holds for , fma and every
elementary function whose result is normal, so the classical forward and
backward error analyses of Higham carry over with .
Design decisions
One representation, many contexts
Problem. Applications need decimal32/64/128 and arbitrary precision, IEEE semantics and GDA compatibility, without converting between types.
Options. One type per format (like hardware); one arbitrary-precision type with the format carried by a context; a type parameterised by the format.
Choice. One Decimal type holding a sign, a coefficient of any length, an
exponent, a class, a NaN-kind bit and a working-precision field, and a
separate immutable DecimalContext. A decimal64 computation is a computation
under DecimalContext::decimal64(); the interchange encoders apply the format
context before encoding. This keeps the arithmetic in one place, lets a caller
work at 50 digits and round to decimal64 at the end, and matches the General
Decimal Arithmetic model. The precision field in the value serves only the
context-free operators and conversions.
Round once, in one place
Problem. Double rounding — rounding an already rounded value again — can change a correctly rounded result.
Choice. Every finite context result goes through one finalization routine that receives an exact result , with possibly much longer than . Operation kernels compute exact integers; they never round. The exceptions are operations whose exact result is infinite — division, square root, elementary functions — and two whose exact result would be needlessly long — a sum with a far smaller addend and an integer power — which are described below; each of them still decides the last digit from exact information.
A single rounding needs a single target exponent. With , the exact value has adjusted exponent , and the correctly rounded result has exponent
the first term keeping digits for a normal result and the second the subnormal grid; the result is , followed by the overflow check (on the value rounded to digits with unbounded exponent), the underflow flag and the fold-down.
The routine rounds to the subnormal grid only when ,
which it tests as : the exact value is
then below and is rounded once with shift
. Every other coefficient is rounded once to digits,
also when . Rounding such a normal result first to the
grid and then to digits would not be rounding once:
if the first rounding lands exactly on a midpoint of the second grid, the tie
rule of the second rounding decides a case the exact value had already
decided. In decimal32 () the product
would first become (the dropped digit
1 is below half), the exact midpoint , and
HalfEven would then give ; the exact value lies
above the midpoint, and the single rounding returns .
(The directed modes would be unaffected, because
for every real and integers .)
Addition with a far smaller addend
When one addend lies far below the other, , the exact sum can have
many more digits than the result keeps. Let be the target exponent of
alone and . Every digit of lies on the grid
, and so does every rounding boundary of the sum: the grid ,
its midpoints, and the grid with its midpoints, which a
cancellation can reach. If , the sum lies
strictly between the same two neighbours on that grid as the short value
, with the sign of . add_ctx
rounds that value once instead of the exact sum; result and flags are the
same in every mode. With precision 7, is 1598616 under Down, and is 6.000001E-73 under HalfEven.
How the rounding digit and sticky information are obtained
Rounding (a non-negative integer with digits) to digits divides by a power of ten,
and decides between and by comparing with . This single comparison carries exactly the information of the classical rounding digit and sticky bit. Write with rounding digit and rest . Then
and since :
So , and mean “above, at, below the
midpoint”, which is all the half modes need; is the sticky
information the directed modes need; and the last digit of is all
ZeroFiveUp and HalfEven need. When the whole coefficient is
discarded, , and only can reach the midpoint: the code then
compares with . A carry that turns into
is removed by one exact division by 10 and an exponent increment.
rounded is raised whenever and inexact whenever ; trailing
zeros are dropped before rounding so that discarding zeros raises only
rounded.
Division
The quotient of two finite non-zero values takes one of three exact routes, in this order.
- Divisor a power of ten. The quotient is with a shifted exponent.
- Terminating quotient. Reduce by to . The quotient has a finite decimal expansion if and only if ; with , so the exact result is the integer with exponent , handed to the finalizer like any exact result. Whether the quotient terminates is decided before any gcd is formed: with and prime to 10, it terminates if and only if divides (the reduced denominator contains no prime of exactly when the gcd takes all of , and is coprime to the factors 2 and 5 of ). The valuations and are read from the lowest limb when both are below 9, so for a divisor prime to 10 (the usual case) the test is , one division of limb arrays. Only a terminating quotient runs the gcd route above; a non-terminating one, which is nearly every division of random operands, used to pay a gcd of the two coefficients (quadratic, hundreds of allocations at 34 digits) to learn that it has no exact result.
- Non-terminating quotient. The result is certainly inexact. Let , found exactly by comparing with scaled by the right power of ten. Scaling the numerator (or the denominator) by makes the integer quotient have exactly digits: . The increment decision compares with — the same midpoint test as above, now with the exact remainder as sticky information — so the quotient is rounded once.
The third route is used for normal results. For subnormal
results the code forms the integer quotient of
by with (about
digits), rounds it with ZeroFiveUp,
and rounds that guarded quotient once more in the context mode, straight to
its final grid: digits, or for a subnormal
quotient. The context-free operator / uses the same guarded scheme. By the
ZeroFiveUp lemma below the two roundings equal one rounding of the exact
quotient, so at five digits is 0.00018009,33 Rounding the guarded quotient in the context mode instead could
manufacture a tie: at five digits the guarded quotient of
would end in an exact half unit, and half-even would return 0.00018008. and in
decimal32 gives 1E-101.
ZeroFiveUp exists precisely to make such two-step schemes safe. If is
first rounded with ZeroFiveUp to digits () and then with
any mode to digits, the result equals : an inexact
ZeroFiveUp result ends in a digit other than 0 and 5, so it is never a
-digit number nor a -digit midpoint, and it lies on the same side of
every -digit number and midpoint as . The proof is in the
attachment.44 Rounding proofs for decimal
contains the full proofs of the double-rounding lemma, the overflow table, the
fold-down bound, the certification lemma and the NTT bound. The guarded division above relies on it; the
finalizer needs no such lemma, because it rounds once at the target exponent
derived above.
Plain sums, products and quotients
The general route of add_ctx, sub_ctx, mul_ctx and div_ctx normalizes
the exact result, finalizes it and returns flags, through temporaries that are
records and tuples: a 34-digit sum made 20 allocations, a product 14 and a
quotient 38. Most operations need none of that machinery. When both operands are
finite and nonzero, the context has a precision , and the result is neither
absorbed, nor subnormal, nor beyond the range, nor folded down by the clamp,
the result is the exact result rounded once to digits, with inexact
raised when a nonzero digit was discarded and no other flag.
The predicates are those of the finalizer turned around. The exact result has
adjusted exponent ; the plain path requires .
Then the result is not tiny (no subnormal rounding, no underflow), and a carry
of the rounding into raises the adjusted exponent to at most ,
so it cannot overflow; the exponent of the rounded result is or one
more after a carry, never below . For an exact result with
fewer than digits the exponent is the exponent of the exact result, and in
a clamping context the plain path requires it not to exceed
(otherwise the finalizer folds the digits down, which the
general route does). A sum also requires that the smaller adjusted exponent is
not below (no operand is absorbed; that case keeps its own
sticky route) and a nonzero exact sum (the sign of a zero sum depends on the
rounding direction); a product and a quotient require nonzero operands. A
quotient with a finite decimal expansion is left to the general route, because
its exponent follows the ideal-exponent rules.
A sum is formed in one limb array and rounded in place by the kernel; a product
is the exact product rounded at the digit count. A quotient is one division of
with (, the digit
counts of the coefficients), which has at least digits, rounded with
ZeroFiveUp and then once to digits, which by the ZeroFiveUp lemma above equals one
rounding of the exact quotient in every mode. The remainder test of that
division tells a terminating quotient from a non-terminating one; for the cheap
cases (equal coefficients, a divisor of one limb) the test is made before the
division, so that an exact quotient does not pay for a division it discards. The flag
sets are shared constants, like the empty set (DecimalFlags is an immutable
record compared by value). A 34-digit add_ctx makes 5 allocations and 1,739
instructions instead of 20 and 4,427, mul_ctx 8 and 2,500 instead of 14 and
3,251, div_ctx 13 and 3,840 instead of 38 and 9,212.
The general route stays the definition of the behavior, and the plain paths are checked against it: the white-box test compares both on random operands of 1 to 130 digits with mixed signs, cancellations, exponent gaps and carries, at every rounding direction, in clamped and unclamped formats with tight and storage-wide exponent ranges, with operands placed at both ends of the range.
Square root
Exact roots are detected first: after removing trailing zeros and making the exponent even, the operand is , and is a decimal if and only if the integer is a perfect square. Such a root is returned at the member closest to the preferred exponent ; if it has more than digits it is rounded like any exact result. For every other operand is irrational.
For the irrational case let the target exponent be . The root has adjusted exponent : from follows , and both for even and for odd the integer part of the exponent is . So leaves digits, or stops at the subnormal grid. When the operand is scaled to the integer and is the truncated root at exponent . When the code takes the integer root of (of if is odd) and divides it by ; nested floors of a positive real by positive integers compose, so this is again . The integer root is computed by the kernel (Zimmermann’s Karatsuba square root from three limbs, see Coefficient kernels); the iteration it replaced, and that the tests keep as the reference, is Newton’s iteration on integers,
( gives ). Because for an integer , the AM–GM inequality gives ; and exactly when . The iterates therefore decrease strictly to , where the iteration stops.
Since the root is irrational it is never exact and never a midpoint, so the increment decision needs only the comparison , done exactly as (or in the second branch). Rounding directly at the subnormal target exponent avoids rounding twice for tiny roots.
A root can be exactly halfway when it is exact but longer than digits:
at gives 2 under HalfEven and HalfDown and
3 under HalfUp. A halfway root squares to
, an odd coefficient with at least
digits when has digits ( gives ). A normal halfway root therefore needs an operand with more than
significant digits, and a subnormal one an operand below the format’s
range. An operand that fits the format (at most digits, value at least
) has a normal root whenever , as in
all interchange formats, because ; for such operands the three half
modes agree.
Exponent range
The finalizer works on the rounded coefficient with digits and exponent , i.e. on the value rounded with an unbounded exponent range.
Overflow
If the result overflows. IEEE 754 §7.4 defines the delivered result as the rounding of the exact value in a format with the same but unbounded exponent, then saturated: a direction that never increases magnitude cannot leave the finite range, a direction that may increase it goes to infinity. Hence, with :
| Mode | ||
|---|---|---|
HalfEven, HalfUp, HalfDown, Up | ||
Down | ||
Ceiling | ||
Floor | ||
ZeroFiveUp |
The half modes go to infinity because an overflowing exact value is at least
(anything smaller rounds to a
finite value and does not overflow), which is at or beyond the midpoint
between and the next power of ten. ZeroFiveUp saturates because
the last digit of is 9. Every overflow raises overflow,
inexact and rounded.
///|
test "design: overflow depends on the rounding direction" {
let ctx = @decimal.DecimalContext::decimal64()
let big = @decimal.Decimal::from_string("9E+384").unwrap()
let ten = @decimal.Decimal::from_int(10)
inspect(big.mul_ctx(ten, ctx).0, content="inf")
let down = ctx.with_rounding(@decimal.DecimalRoundingMode::RoundTowardZero)
let (sat, flags) = big.mul_ctx(ten, down)
inspect(sat, content="9.999999999999999E+384")
inspect(flags.overflow() && flags.inexact(), content="true")
}
Subnormals, tininess and underflow
If the exact value is below and needs an exponent below
, it is rounded once to the subnormal grid: the shift becomes
and the rounding rule above applies with fewer than
digits kept. The result is tiny when its adjusted exponent is below
, measured on the exact value. IEEE 754-2019 §7.5 requires this for
decimal formats (“tininess is detected before rounding”); the binary-style rule,
on the value rounded to digits with unbounded exponent, was an option of the
library until 0.12 and is gone. With and , and
are both tiny (their subnormal-grid result is 1.00). A tiny and inexact result raises underflow, as IEEE 754
§7.5 requires for default exception handling. A result that rounds to zero
gets exponent .
Clamping
In every context, exponents above are not representable, because the encoding has room only for exponents. A result with that did not overflow is folded down: the coefficient is multiplied by and the exponent set to . This never needs more than digits:
using . The value is unchanged; only the
cohort member changes. In decimal32, 1E+96 is stored as 1000000E+90.
///|
test "design: fold-down in decimal32" {
let ctx = @decimal.DecimalContext::decimal32()
let (x, flags) = @decimal.Decimal::from_string_ctx("1E+96", ctx)
inspect(x.coefficient(), content="1000000")
inspect(x.exponent10(), content="90")
inspect(flags.inexact(), content="false")
}
Zeros have no digits to pad, so their exponent is simply clamped into .
A zero is the one result quantize_ctx can return above : its
target exponent only has to be at most (a zero has one digit, so
is the overflow bound of
decNumber’s decQuantizeOp). decNumber calls decFinalize there, whose clamp
branch lowers the exponent to . A result
of an IEEE format is a member of the format (§3.3), whose exponents stop at
, so quantize_ctx folds a zero like every
other operation does through finalize_finite_ctx; until 0.12 the fold of these two
was an option (with_clamp_fold).
Flags as returned values
Problem. IEEE 754 status flags are sticky process state in hardware; GDA adds traps. Hidden state conflicts with the Luna-Flow rule that semantics are explicit, and makes concurrent or compositional code fragile.
Choice. Each context operation returns its own DecimalFlags.
combine is the field-wise OR, so flag sets form a commutative idempotent
monoid with identity DecimalFlags::new(): accumulating them over a pipeline
in any grouping gives the same set, which is exactly the sticky-flag
semantics without the state. DecimalFlags is an immutable record compared by value, so the identity is
one shared value and combine returns the other operand when one is clear:
no flag set is allocated for an operation that raises nothing. decimal_checked packages that accumulation;
decimal_gda implements sticky status and traps as a separate model. The
five IEEE exceptions are invalid_operation, division_by_zero,
overflow, underflow and inexact; DecimalFlags has exactly these and
not_computed. The GDA conditions (rounded, subnormal, clamped,
lost_digits, conversion_syntax, division_impossible, division_undefined,
invalid_context) belong to decimal_gda.
Quantize and same-quantum
x.quantize(y) returns the value of with exponent exactly :
The result must be representable at that exponent: the new coefficient must
have at most digits, must lie in and the
result’s adjusted exponent must not exceed . Otherwise the operation
is invalid. It never substitutes another exponent, because the exponent is
the contract (an amount quantized to cents must have two decimal places). The
only change of exponent is the fold-down of clamping: a target is accepted and the
result is stored at , exactly like any other
result in that range.
Rounding a coefficient up can add a digit ( at two digits of
precision), which is why the digit check comes after rounding.
same_quantum is the predicate (true for two infinities or two
NaNs); it is the test to use before combining values whose exponents must
agree.
Conversion to integers
to_int_ctx and its three siblings (IEEE 754-2019 §5.4.1 and §5.8) share one
function that rounds a finite value to an integer in the direction
of the context and checks the range, so the four types differ only in their
limits. A value with is an integer already; one with is
rounded by the same decision function that rounds decimal
results (the kernel’s rounding decisions: increment or not from the discarded
digits and the mode), and changed is whether anything was discarded.
The power of ten is never formed. An integer of 21 or more digits is out of
range for every type ( has 20 digits), so
is decided before any arithmetic, and a fraction with more than
places is the same as one with exactly that many:
the value is below , and the rounding decision only needs to know that the
remainder is nonzero and below one half, so the shift is clamped to
. 1E+999999 and 1E-999999 therefore cost
as much as 1E+3 and 1E-3. The invalid operation is signaled for a NaN, an
infinity and an out-of-range result, and then only: exact adds inexact
when changed, nothing else is ever raised (no rounded, no clamping: the
result is not a decimal), and a negative value that rounds to zero converts to
0.
Conversions between formats
convert_format, from_binary_ctx and to_binary_ctx (IEEE 754-2019
§5.4.2) are thin on purpose: each rounds the exact source value once, in the
destination’s context, and returns the flags of that rounding.
Decimal to decimal is apply_ctx of the format’s context, so the preferred
exponent is the one the normalization keeps when the value
fits. Binary to decimal does not form the expansion , whose cost grows
with : it takes the first significant digits of , truncated, from
the correctly rounded digit string of Binary::to_decimal_string_ctx, appends a
sticky digit when digits were dropped, and rounds that decimal once with
apply_ctx. A rounding of a decimal depends on the digits beyond the kept ones
only as zero, below half, a tie or above half, and the surrogate (the digits and
the sticky digit) lies strictly inside the unit after the truncated digits as
does, so for every kept length up to (fewer digits for a subnormal result, so
nothing is rounded twice) the result and its flags are those of , and the
tininess of the unrounded value is the one of (same leading digit). An exact
value has no sticky digit; its trailing zeros are dropped and an integer takes
exponent 0, the preferred exponent, or, when it has more than digits, the
member closest to it (IEEE 754-2019 §5.2): zeros are appended up to digits,
and the zero that apply_ctx rounds away leaves the -digit member with the
exponent closest to 0 (1E+20 in decimal64 is 1000000000000000E+5, flagged
rounded). The digits are not
formed for a value whose estimate
lies more than two beyond
or three below , which stands for every such value in
the rounding (overflow, or a result of zero or the least subnormal). A binary exponent
beyond is refused. Decimal to binary is the exact decimal text rounded by
Binary::from_string_ctx, which is correctly rounded for any exponent and is
checked against MPFR; the corpus runs both directions through the MPFR rows of
mpfr_strtofr and mpfr_get_str and through exact rows for every pair of
decimal32/64/128 and binary16/32/64/128 (tools/generate_decimal_conversion_rows.py).
A NaN keeps its sign and the payload it can hold ( digits, bits),
and a signaling NaN is quieted with the invalid operation exception.
Interchange encodings
All three formats share one layout: a sign bit, a 5-bit combination field , exponent continuation bits and a trailing significand of bits, where :
| Format | |||
|---|---|---|---|
| decimal32 | 6 | 2 | 32 |
| decimal64 | 8 | 5 | 64 |
| decimal128 | 12 | 11 | 128 |
The biased exponent has bits whose top two bits take only the values 00, 01, 10; this is the count derived above.
DPD. The combination field holds the top two exponent bits and the leading digit : if with , the exponent bits are and ; if with , the exponent bits are and . is infinity and is NaN, the next bit distinguishing signaling from quiet. The other digits are stored in declets, 10 bits for 3 digits, by densely packed decimal.55 M. F. Cowlishaw, “Densely packed decimal encoding”, IEE Proceedings — Computers and Digital Techniques 149(3), 2002. IEEE 754-2019 §3.5.2 gives the encoding tables; the code implements them as Boolean formulas, and the conformance corpus checks all 1024 declets. Three digits have 1000 values and 10 bits 1024 codes, an efficiency of . Call a digit small if it is 0–7 (3 bits) and large if it is 8 or 9 (1 bit). The declet uses for three small digits, which are then stored verbatim in , , ; marks at least one large digit, and , then , say which. Counting by the number of large digits,
and . The first three cases use exactly 512, 384
and 96 codes. The last case has 32 codes for 8 values: , ,
carry the low bits of the three digits and , are ignored, so 24 codes are redundant: each
value with three large digits has four encodings, of which the one with
is canonical. Decoding accepts all four, canonical() rewrites them.
For example, 125 is the declet 0010100101 = 0x0A5 (three small digits)
and 999 is 0011111111 = 0x0FF, also written 0x1FF, 0x2FF, 0x3FF.
BID. The coefficient is stored as a binary integer. If the two bits after the sign are not 11, the next bits are the biased exponent and the remaining bits the coefficient. Otherwise the exponent follows the 11 and the coefficient is plus the remaining bits (“100” implied). Since , and , every coefficient fits; encodings with a coefficient are non-canonical and decode to zero.
///|
test "design: redundant DPD declets decode and canonicalize" {
let fmt = @decimal.DecimalInterchangeFormat::Decimal64
let canonical = @decimal.DecimalInterchange::from_hex("#22300000000004FF", fmt).unwrap()
let redundant = @decimal.DecimalInterchange::from_hex("#22300000000007FF", fmt).unwrap()
inspect(canonical.to_decimal(), content="19.99")
inspect(redundant.to_decimal(), content="19.99")
inspect(redundant.is_canonical(), content="false")
inspect(redundant.canonical().to_hex(), content="#22300000000004FF")
}
DecimalInterchange keeps the raw bits so that non-canonical input survives
until the caller decides to canonicalize; arithmetic is always on Decimal.
Certified elementary functions
Problem. For transcendental , is irrational for almost every decimal , so it can only be approximated; a correctly rounded result needs an approximation good enough to decide the rounding (the table maker’s dilemma).
Options. A fixed-precision evaluation with an a-priori error bound (fast, but correctness then depends on the bound being right for every function and argument); Ziv’s adaptive strategy66 A. Ziv, “Fast evaluation of elementary mathematical functions with correctly rounded last bit”, ACM TOMS 17(3), 1991; J.-M. Muller et al., Handbook of Floating-Point Arithmetic, 2nd ed., Birkhäuser 2018, ch. 12; J. van der Hoeven, “Ball arithmetic”, 2009, for the enclosure model. with rigorous error bounds.
Choice. A Ziv loop over rigorous enclosures. For an operation and input :
- Convert exactly into a binary interval: and ,
to_binarywithRoundTowardNegativeandRoundTowardPositiveat bits, so . - Evaluate on that interval with
interval, which returns an interval for every point of the input interval. - Convert and (dyadic, hence exact decimals) to
Decimalexactly and round both with the target context. If both give the same representation (total_order_compareequal) and the same flags, return it. - Otherwise increase and
repeat; after evaluations report a certification failure, where is
the refinement limit of the context (
DecimalContext::refinement_limit, twelve by default; a value below one counts as one). Withwith_refinement_limit(None)the count is unbounded, but the loop stops, with the same failure, when exceeds bits (at most ), so the work and the memory stay bounded. The default changes no result.
The acceptance test is sound because rounding is monotone:
implies , and if the
outer two are the same representation, so is the middle one. The flags
transfer as well, provided is not itself representable: then one
endpoint differs from the common result, so both are inexact, and
overflow and underflow are monotone in on an
interval that does not contain zero. Representable results are therefore
handled before the loop (below).
The initial working precision is bits, where is the number of input digits: one decimal digit needs bits, so bits represent the input and the target, and 31 guard bits more cover the loss of the enclosure. The schedule grows by a factor of about per step (exactly once ); the 12 evaluations use , and the last one works with about bits.
Three kinds of inputs are decided outside the agreement test:
- Exact results. If is a representable decimal and the enclosure
is not a point, round to different neighbours in a directed
mode, forever. In a half mode both endpoints round to itself, but
with
inexact, so the agreement test would accept the right value with wrong flags and with all digits instead of the preferred exponent: the soundness argument above assumed that is not representable. The code therefore detects exact cases before the loop (exp(0),ln(1), , integer and half-integer arguments ofsinpi/cospi/tanpi, odd quarter-integers oftanpi,acos(1), integer arguments ofexp2/exp10, , integer powers, …). For the algebraic functions this is a finite integer computation:rootnstrips the trailing zeros of the coefficient, aligns the exponent to a multiple of the degree and tests the integer -th root (Newton’s iteration from above) of the result, so ;hypotforms exactly when the adjusted exponents of the operands differ by at most (beyond that, is below the last digit the result could have) and tests it with the exact square root, so ; a zero operand gives the other operand’s magnitude.intervalreturns point intervals for exact binary results such as , and . A power whose exact value is representable in decimal but not in binary is decided in decimal instead: the exponent is reduced to in lowest terms — a decimal exponent is , so keeps only the twos and fives the coefficient cannot cancel — and the result is exact exactly when is a decimal. By Bézout there are integers with , so is rational whenever is, and a rational -th root of a decimal is again a decimal (its denominator divides a power of ten). The test therefore writes with an integer keeping fewer than trailing zeros, decides whether is a perfect -th power by a bisection over the root’s digit count, and only then raises the root to (the reciprocal of the root, for a negative exponent). Every intermediate is then no longer than the result, so , and at precision 1000 are all decided at once, although in the last one has 1084 digits. Only a value of at most significant digits can sit on a rounding boundary — a representable value in the directed modes, a midpoint in the half modes — so the search covers exactly those and leaves a longer exact value, which lies strictly inside its rounding cell, to the enclosure. - Integer powers are not certified; they are rounded once from exact
integer information.
pow_ctxwith an integral exponent that does not fit in digits first runs the General Decimal Arithmetic square-and-multiply with working digits. That scheme only ever discards zero digits of an exact power, so it reportsinexactexactly when the true power is inexact, and it gives exact powers their GDA cohort and flags. An inexact result is then replaced by the correctly rounded one. With the coefficient stripped of trailing zeros, if the exact power is formed and rounded once (a negative divides once, correctly rounded). Otherwise has more than significant digits and no trailing zero, so it is never a -digit number or midpoint; lower and upper bounds from square-and-multiply inDownandUpat a working precision of digits, doubled on each attempt, are refined until they round to the same representation. So is37.24077in decimal32. If the bounds leave the working exponent range, the GDA result is kept; its error is below one unit in the last place. A power that the exponent bounds place below (including an exact power of ten below ) is not evaluated: it rounds like any non-zero value below , to zero in the nearest modes and to when the rounding direction is away from zero for its sign (IEEE 754-2019 §7.5). - Out-of-range results. An enclosure such as has
endpoints that round with different flags. Any value
overflows identically, and any non-zero value
rounds identically (to zero or to the
smallest subnormal, depending only on the mode and sign), so far endpoints
are replaced by such representatives; the binary test uses so the replacement is conservative.
exp,exp2andexp10share one decision (decimal_exponential_coarse_extreme_result, issue #363). For with let be the integer 3, 4 or 1. Then gives , above the largest finite number , so the overflow result of the rounding direction applies (IEEE 754-2019 §7.4); and gives , below half of the smallest subnormal and, as , tiny before and after rounding, so the result is zero or the smallest subnormal by direction withinexactandunderflow(§7.5). The comparison is exact and the margin is the whole slack between and : an argument between the true boundary and the threshold is not decided here but by the Ziv loop, which is sound there because the threshold is at most with , far below the exponent range of the binary enclosure. Without the decision a very negative argument (forexp2, beyond binades) has the enclosure and never certifies. The decision is tested on both sides of each threshold and at results just inside and outside the range, in all eight rounding directions, bylibrary/src/decimal/exp_range_wbtest.mbtand its generated rows.powerbounds with directed 128-bit arithmetic for the same purpose. - Enclosure of a non-integral power. For a positive base the Ziv loop
evaluates in interval arithmetic: one
lnenclosure, one interval product and oneexpenclosure, instead of the four corners times two directions (eight correctly rounded binary powers) ofinterval’stry_pow. The loop needs an enclosure, not tight endpoints, and correct rounding makes the delivered value independent of the enclosure’s width, so the result, cohort and flags are those of the tighter evaluation. The composition loses about bits of relative accuracy, because the relative error of is the absolute error of . The initial working precision therefore grows by a bound of that quantity, taken from the adjusted exponents of and ( and ), so the first attempt usually decides (#352).
One layer for the newer §9.2 functions. exp2m1, exp10m1, log2p1
and log10p1, and the families that follow in
#236, take three
decisions from one internal file (elementary_range.mbt) instead of writing
them again: an exact result is formed as an exact decimal, rounded once by the
context and then moved to the cohort member nearest the preferred exponent
(decimal_exact_constant, which uses the cohort step of power with the
preferred exponent as an argument), so a context that cannot hold the value
rounds it with its own flags; a result whose certified bracket of
lies above or below
rounds like the representative
or
(decimal_range_from_log2_bracket, the former tail of the power range
test); and every other result comes from the Ziv loop above. No result is a
zero or an infinity chosen because the argument is small or large: a tiny
result is the rounding of its certified endpoints, so subnormals, Underflow
under the before-rounding rule and the sign of a zero are those of the
context.
The four functions evaluate expm1(x ln b) and log1p(x) / ln b on the
input interval ( and as certified interval intervals).
Both primitives are series in , so the relative width of the enclosure is a
few units of the working precision for every legal operand, down to
; no tiny-argument anchor is needed because the slopes
and are irrational. Before the loop:
- Exact cases. is rational only for an integer ( and
are irrational for a non-integer rational ), and is
rational only when . For the value ,
, or is formed and rounded once;
is found from without forming ( a power of two, compared
first on its lowest nine digits; all nines; a coefficient or
with fraction digits). The preferred exponent is 0
(IEEE 754-2019 §9.2.2), so
exp2m1(4)is15andlog2p1(-0.50)is-1. - Clusters. For an integer , has digits and
every rounding boundary of a -digit integer is a multiple of the even
number ; neither (no factor 5) nor the odd
is one, so both lie in one open rounding cell and
exp2m1(n)isexp2(n). lies above the midpoint and below , where an enclosure can never separate it from the representable ; the representative has the same rounding and is formed instead of a number of digits. Towards , for (base 10) or (base 2) the value is with and rounds like , as forexpm1. - Overflow. (base 2) or (base 10) gives the overflow result of the context.
- Below the subnormal range. For all four satisfy with the sign of , so puts below , where it rounds like the representative that the enclosure would use for its endpoints. The result is that rounding, decided without converting to binary (the conversion of alone costs about a second).
- Tiny arguments within the range. For , write
; then with or
and , so lies in
for . The endpoints of that
enclosure have a few dozen digits, where the binary endpoints of
itself would expand to about digits; scaled back by they
are rounded with the context and accepted under the same agreement test as
the loop, which decides the rare value too close to a rounding boundary.
The certified and intervals are kept per working
precision. Both only change the cost: on 10,000 random rows of each function
the executed instructions fell from 57 to 12 (
exp2m1), 60 to 14 (exp10m1), 102 to 17 (log2p1) and 102 to 18 (log10p1) billion, the level ofexp(13) andlog1p(18). - Poles and domain. is with
division_by_zeroand is invalid forlog2p1andlog10p1(Table 9.1). Near an operand of digits keeps , which resolves, as forlog1p.
rSqrt, compound and powr. The three take their exact results from
decimal_exact_constant and none of them expands a binary endpoint near an
extreme power of ten.
rsqrt. terminates exactly when : with the coefficient stripped of trailing zeros and its exponent, is or with (or ) and even, and the value is or . It is formed when it has at most digits and given the preferred exponent (§9.2.2); a longer one ends in a 5 or a non-zero even digit beyond the -th place, so it is neither representable nor a midpoint, and the enclosure decides it. Every other is written with : the Ziv loop encloses , whose endpoints are moderate, and multiplies them by (an exponent shift) before the context rounds them, under the same agreement test. An operand costs what costs.compound. The special values are the list of §9.2.1 (with invalid also for , Table 9.1). For a tiny , has the sign of and for , sodecimal_tiny_argument_resultdecides a one-sided neighbour of 1 and (up to two million digits) is never formed. Otherwise is formed exactly ( without trailing zeros, digits, exponent before stripping). For , has more than digits and no trailing zero, so beyond digits it is neither representable nor a midpoint; shorter powers are formed and rounded once with the preferred exponent . For , terminates only for or (the values and ), formed while they have at most digits. Every other case is the Ziv loop on ( of itself, so is never rounded), afterdecimal_range_from_log2_bracketon whenever does not already keep the result inside the range.Int32’s minimum is taken as anInt64.pown(1 + x, n)is not used: when this function was written, its exponents beyond the machine count gave wrong values and some negative ones a spuriousClampedfor a base near 1 (issues #348 and #350, since fixed), and the Ziv loop never forms .powr. §9.2.1 lists the invalid pairs , , and , and a NaN result for a NaN operand even when . Two cases are not stated and are read as follows: with a quiet NaN is invalid (the NaN rule is stated “for ”), and for and for follow by continuity. Every remaining pair has , where is the same function aspow, and the preferred exponents agree (), so the result ispoweron (a is passed as , wherepowwould apply its odd-integer sign rule).
asinPi, acosPi, atanPi and atan2Pi. The four evaluate
, ,
and in the
existing Ziv driver, with enclosed as
taken from the cached binary-splitting constant of binary (twice the
correctly rounded of atan(+inf), the same interval as
bit for bit) and the angle
enclosure divided by it (error: the angle, and the division, about
4 ulp relative).
- Exact results. By Niven’s theorem a rational has a rational
or only at
and a rational only at
, so the dyadic exact results are those of §9.2.1 and
,
. They are
built by
decimal_exact_constantat the preferred exponent 0 (§9.2.2). , and do not terminate, so they sit strictly inside a rounding cell and the loop decides them. No Pi function is anchored at a tiny argument: is irrational and nowhere near a representable value. - Clusters next to and . These are the only inexact
results that approach a representable value, and the distance does not
depend on the digits of the operand, so a that grows with cannot cover it.
Each is decided by
decimal_tiny_argument_resultfrom a bound on the distance, one-sided: with for a large ; with distance at most for a tiny (the easy one to miss: of a tiny is near the irrational , but is near the representable , below it for and above for ); with is with for a large ratio (below in magnitude for , above for ), and with for and a small ratio. The guard ofdecimal_tiny_argument_result(error exponent below the anchor’s adjusted exponent minus ) picks the threshold; between it and the moderate range the enclosure resolves the gap at the working precision. The tests compare every anchored result with the plain loop in all eight rounding modes, on both sides. - Tiny results. For , and , and the same
holds for with and the ratio .
Once the loop encloses the moderate value
with (or the
quotient of the two scaled mantissas) and shifts the endpoints by
before the context rounds them, as for
rsqrt(decimal_certified_scaled_result): an operand costs what costs, where the exact decimal endpoints of a binary number near have about two million digits (an unscaledasinpi(7E-9999)took more than a minute in a debug build before this path existed). For with the derivation is: with , where are the operands scaled by their adjusted exponents and , so ; for , , hence with , , and the loop encloses the moderate factor , , and shifts it by . The path is taken when , where it is decidable; the derivation itself needs only . The operands of every other case are first multiplied by (the ratio, hence the angle, is unchanged), so operands with exponents of millions of digits and a moderate ratio cost what moderate operands cost.library/src/decimal/atan2pi_scaled_wbtest.mbtand the generated rows oftools/generate_decimal_atan2pi_scaled_rows.py(Pythondecimalat 450 digits, a cross-check only) cover ratios on both sides of the condition, both signs of and of (for the result is , next to , and takes the other anchored path), the four formats and all eight rounding directions; replacing by or the condition by makes rows fail (checked by mutation).
Operands of extreme exponent and the cost of a first attempt
Four changes of issue #378 keep the cost of a call independent of the size of its operands’ exponents while the results stay those of correct rounding.
- Conversion to binary. For the quotient is formed once, with (so and the quotient keeps at least bits: two bits below the target position and a sticky bit), made odd when the remainder is not zero; the remainder test is a multiplication, not a second division, and the lower and upper bound of a ball come from the same quotient. For the exact (rebuilt on every call above the power cache) is replaced by a lower and an upper bound with of bits, made by binary powering with a directed trim after every product; the two bounds are rounded in the requested mode and the result is kept only if they agree (monotonicity of rounding), otherwise the exact conversion decides, so the result is the exact conversion bit for bit. For a negative exponent the quotient of the bounds is used only when , where guarantees that the division is inexact (the sticky bit is set).
- First working precision. bits instead of : the schedule grows by a factor of 1.5 when an enclosure does not decide, so a low start costs an attempt and never a result. On 16,536 rows (exp, exp2, exp10, expm1, the inverse functions of and atan2Pi, five formats) the number of operand conversions was 14,489 before and 14,490 after.
- Tiny arguments of exp, exp2, exp10, expm1 and log1p. For ,
: for
(, ) with the sign of , so
the result is plus or minus less than , one-sided next to the
representable 1 and decided by
decimal_tiny_argument_resultonce ; and , , both below for , so expm1 lies above and log1p below it, within . Rows on both sides of the thresholds, both signs, three formats and all eight directions have independently computed expected values; flipping a side makes rows fail. - Exact tests before the loop. An exact -th root of a decimal needs
once trailing zeros are removed (
with and has or
equal to the shift, not a multiple of ), and the root comes from the kernel
(square roots first for even degrees, Newton from the root of the leading
digits);
atan2forms the exact ratio only when with , the necessary condition of the tiny-argument decision;compounddoes not form when is an integer multiple of 10 with (the sum ends in 1: no power of 2, 5 or 10) or for when (more than digits);sqrtreuses the remainder of the integer root. - Negative integer power (#375). For , with , , hence : it overflows when and lies below half of the smallest subnormal when ; the exponent product of the exact path is formed in 64 bits.
Outward-rounded endpoints
The Ziv driver turns the two binary endpoints of an enclosure into
decimals and rounds both to the context. Expanding exactly
costs , about digits, which is quadratic in the decimal
exponent of the argument under a wide-range context (1E-999990 took more than
80 s in expm1). For a non-degenerate enclosure the driver instead rounds
down and up to digits, being the bit
length of the endpoint coefficients (so a refined enclosure is never widened
beyond about one binary ulp). The powers and are computed by
binary powering with a directed trim to digits after every product:
products of -digit numbers, independent of .
Soundness. Every trim moves towards the chosen side (down for the lower magnitude bound, up for the upper one, with signs swapped for negative endpoints), and products of positive bounds are bounds, so by induction the computed power brackets the exact power, and . Rounding to the context is monotone, so implies is that value for every , and the flags are compared as before. The guard digits only affect tightness, not soundness. A degenerate enclosure (, binary-exact) keeps the exact expansion, and infinite, zero and out-of-range endpoints are converted as before. A certified result is unchanged; only an enclosure that straddles a rounding boundary at a distance below relative is refused one step earlier, and the next refinement widens with the binary precision.
The elementary functions and the pow family refuse contexts with or above 999,999 for an ordinary operand (the precision part is the field elementary_precision_limit of the context, Some(999_999) by default and None for no limit, an escape entry with no guarantee of time or memory); the special operands and the exact points of IEEE 754-2019 9.2.1 are answered first, in every context, and the limit is tested before the first step that computes
(not_computed, and Err of the certification-failure kind in the try_ forms; the decNumber limit, see the decimal_gda design page),
which bounds the size of the exact endpoint conversions.
Coefficient kernels
Problem. Rounding at decimal positions needs fast division by powers of ten and fast digit counts; large precisions need sub-quadratic multiplication and division.
Choice. DecCoeff, defined in the internal package
internal/decimal_kernel that decimal shares with decimal_gda (neither
package exposes it), is either a Small(UInt64) below or a
little-endian array of base- limbs with no leading zero limb and a
cached digit count. The package holds only status-free integer arithmetic;
the finalizer, flags and contexts stay in each decimal package (see
the shared kernel). Base is the largest power of ten below
, so a limb product is below ; shifting by a
multiple of nine digits moves limbs, and digits10 is a limb count plus the
digits of the top limb. BigInt appears only at the public boundary.
Multiplication dispatch:
| Shape | Algorithm | Cost |
|---|---|---|
| one limb each | inline | |
| many zero limbs ( non-zero limbs) | sparse products | |
| balanced blocks of the short length | ||
| small | Comba columns / schoolbook | |
| from the Karatsuba threshold | Karatsuba | |
| from the Toom-3 threshold | Toom-3 | |
| from the NTT threshold | two-prime NTT |
The Comba kernel accumulates a column of limb products in a UInt64
only when : a column sum plus incoming carry is at most
, while 19
products could exceed .
The NTT splits the coefficients into base- digits and convolves them modulo the primes and , both of which have -th roots of unity, so transforms up to length exist. A convolution coefficient is a sum of at most products of digits below , hence below ; it is recovered exactly from its residues by the Chinese remainder theorem,
as long as , i.e. . The transform limit allows at most , and , so the bound always holds below the transform limit (the kernel checks it before every transform). Base digits would need , impossible for any , which is why the NTT uses smaller digits. When the bounds do not hold the kernel falls back to Toom-3.
Division uses one-limb division, Knuth’s Algorithm D,77 D. E. Knuth, The Art of Computer Programming, vol. 2, 3rd ed., §4.3.1 (Algorithm D) and §4.3.3; R. Brent and P. Zimmermann, Modern Computer Arithmetic, Cambridge 2010, §1.3–1.4 and §2.4 (NTT); C. Burnikel and J. Ziegler, “Fast recursive division”, MPI-I-98-1-022, 1998. Burnikel–Ziegler recursive division, or Newton reciprocal division. Newton computes for by : with one gets , so the number of correct limbs doubles per step. The iteration must increase monotonically from below; if it does not, or the final quotient correction takes more than steps, the routine falls back to Burnikel–Ziegler, which itself falls back to Algorithm D on unsupported shapes.
The integer square root with remainder , and
, is Zimmermann’s SqrtRem88 P. Zimmermann, “Karatsuba Square Root”, INRIA research report
RR-3805, 1999 (the algorithm and its proof, with the condition );
Brent and Zimmermann, Modern Computer Arithmetic, Algorithm 1.12 (§1.5.1). on limbs. With
limbs, limbs per block and ,
write with ; the root and
remainder of come from the recursion, , and
, and if then and
. The report proves that this is correct, with this single
correction, when the top part has . With
the block has at least limbs, so
for every radicand with a non-zero top limb and no scaling is needed (the binary
kernel scales its radicand by an even power of two because its blocks are
halves of an even limb count). The quotient is at most (because
and ), and a quotient of exactly is capped to
with added to . The division by is the division of
by (the remainder is ), so is
never formed and cannot carry out of the limbs of ; the divisor is
normalized for Algorithm D. Up to four limbs the base case takes a root of at
most 18 digits from a double estimate corrected with exact limb arithmetic, and
the word root covers one and two limbs. The Karatsuba root is faster than the
Newton iteration from three limbs on, so there is no crossover to a Newton path:
at 3, 8, 32, 128 and 512 limbs it takes 2,096, 6,465, 15,369, 66,536 and 594,956
instructions against 7,967, 24,168, 74,345, 341,256 and 3,627,494. The square of
the quotient block is a schoolbook product up to 16 limbs and the kernel’s
square above. For rounding, the scalar entry returns the root and how the
remainder compares with it (zero; at most ; above ), since
iff , without building the remainder. The
white-box tests compare it with the Newton reference for every length from 3 to
70 limbs, squares and their neighbours, powers of ten, every recursion depth
from 0 to 6, a class that caps the quotient and a class built to take the
correction step.
The crossovers are measured per target and stored in target-specific files:
| Target | Karatsuba mul / square | Toom-3 | first NTT mul / square | Burnikel–Ziegler | Newton |
|---|---|---|---|---|---|
| native | 96 / 48 | 1,152 | 1,728 / 640 | from 2,816 | disabled |
| LLVM | 96 / 96 | 2,048 | 4,096 / 2,048 | 2,048 | 4,096 |
| Wasm / Wasm-GC / JS | 96 / 96 | 4,096 | 8,192 / 4,096 | 2,048 | 4,096 |
(limbs of nine digits). On native the NTT threshold also depends on the transform length — 1,728, 2,816, 4,608, 7,680, then 8,192 limbs for multiplication and 640, 1,040, 1,824, 3,648, 7,296, then 8,192 for squaring — and the Burnikel–Ziegler entry moves to 5,120 and 10,240 limbs for larger block lengths. These are dispatch boundaries: they change cost, never results. The native Newton path is implemented and tested but disabled, because native measurements do not show a crossover.
Correctness and invariants
- Representation. A finite
Decimalhas ;DecCoefflimbs are canonical (no leading zero limb, exact digit count). A zero’s sign is kept in the sign bit;coefficient()never carries a sign. - Single rounding. Every context result of
+,-,×,/,fma,sqrt,scaleb, quantize and the conversions is the exact result rounded once, in the normal and in the subnormal range; integer powers are correctly rounded; certified elementary results are correctly rounded whenever they are returned, and a failure is reported, never approximated. The exceptions are listed under known deviations. - Error bound. For normal results of those operations, with in the half modes and in the directed modes.
- Exactness is visible.
inexactis raised if and only if the returned value differs from the exact result;roundedwhenever digits were dropped. - Cohort preservation. An exact result that fits is returned at the
preferred exponent;
quantize_ctxeither returns exponent or fails. - Flags.
combineis associative, commutative and idempotent with identitynew(). - Ordering.
compareis a total preorder (NaNs equal to each other and above every number, );total_order_compareis a total order on representations and refinescompareon non-NaN values. - Encodings. Decoding then encoding canonical bits is the identity; encoding then decoding a value that fits the format is the identity, including cohort, sign of zero and NaN payload (DPD and BID).
- Complexity. Comparison, addition, shifts and one-limb division are in limbs; multiplication and division follow the dispatch table.
Known deviations
No behaviour of the current branch contradicts the goals above. A deviation found later is listed here, reproduced in the API reference next to the operation, and tracked in a GitHub issue together with the pull request that proposes a fix.
The proofs of the midpoint test, the ZeroFiveUp double-rounding lemma, the
overflow table, the fold-down bound, the certification lemma and the kernel
bounds are collected in the attachment:
The conformance page records the finite evidence (fixed IEEE corpus, exhaustive declet check, MPFR-certified elementary rows, four targets).
Alternatives rejected
- A binary
BigIntcoefficient. Rounding at a decimal position needs a division by and a digit count at every operation; with a binary coefficient both are expensive, with base- limbs they are limb moves and one small division. - Ambient context and sticky flags. Rejected for explicitness and composability; the flags monoid gives the same information.
- A
comparethat aborts on NaN. Sorting and genericComparecode would abort on data containing NaN. The currentcompareis a total preorder and IEEE semantics are available throughcompare_checked,compare_quiet,compare_signalingandtotal_order_compare. - Fixed-precision transcendental kernels with an analytic error bound. Faster for small precisions, but a correctness proof per function and per precision; the enclosure loop is correct by construction and its failure mode is explicit.
- One package for IEEE and GDA. Sticky status, traps and trap precedence
change the type of every operation; they live in
decimal_gda. - Normalizing every result. Losing the cohort would make
12.30and12.3indistinguishable and break quantum-sensitive protocols.
Boundaries
decimal deliberately does not:
- keep sticky status or traps (use
decimal_checkedordecimal_gda); - round the context-free operators to a context:
*is exact,+and/round to the operand precision only, and none applies an exponent range; - guarantee that elementary-function certification succeeds: after the
refinement limit of the context (twelve by default,
with_refinement_limit; the last steps work with very wide numbers and can take a long time) it reportsCertificationFailure(try_*_ctx) or NaN withinvalid_operation(*_ctx); - evaluate elementary functions of an ordinary operand in contexts with precision or exponents above 999,999 (special operands and the exact points of IEEE 754-2019 9.2.1 are answered first, in every context);
- preserve NaN payloads through binary conversions;
- expose its coefficient representation, kernel selection or thresholds;
- claim conformance beyond the finite evidence on the conformance page.
Footnotes
-
IEEE Std 754-2019, Standard for Floating-Point Arithmetic, clauses 3.3–3.5 (decimal formats and encodings), 4 (attributes and rounding), 5 (operations), 7 (exceptions) and 9 (recommended operations). The General Decimal Arithmetic specification by M. F. Cowlishaw (version 1.70) gives the same model in an arbitrary-precision form; its terms coefficient, adjusted exponent, Etiny and clamp are used here. ↩
-
Goldberg, “What every computer scientist should know about floating-point arithmetic”, ACM Computing Surveys 23(1), 1991, §1.2; Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM 2002, §2.1–2.2. ↩
-
Rounding the guarded quotient in the context mode instead could manufacture a tie: at five digits the guarded quotient of would end in an exact half unit, and half-even would return
0.00018008. ↩ -
Rounding proofs for decimal contains the full proofs of the double-rounding lemma, the overflow table, the fold-down bound, the certification lemma and the NTT bound. ↩
-
M. F. Cowlishaw, “Densely packed decimal encoding”, IEE Proceedings — Computers and Digital Techniques 149(3), 2002. IEEE 754-2019 §3.5.2 gives the encoding tables; the code implements them as Boolean formulas, and the conformance corpus checks all 1024 declets. ↩
-
A. Ziv, “Fast evaluation of elementary mathematical functions with correctly rounded last bit”, ACM TOMS 17(3), 1991; J.-M. Muller et al., Handbook of Floating-Point Arithmetic, 2nd ed., Birkhäuser 2018, ch. 12; J. van der Hoeven, “Ball arithmetic”, 2009, for the enclosure model. ↩
-
D. E. Knuth, The Art of Computer Programming, vol. 2, 3rd ed., §4.3.1 (Algorithm D) and §4.3.3; R. Brent and P. Zimmermann, Modern Computer Arithmetic, Cambridge 2010, §1.3–1.4 and §2.4 (NTT); C. Burnikel and J. Ziegler, “Fast recursive division”, MPI-I-98-1-022, 1998. ↩
-
P. Zimmermann, “Karatsuba Square Root”, INRIA research report RR-3805, 1999 (the algorithm and its proof, with the condition ); Brent and Zimmermann, Modern Computer Arithmetic, Algorithm 1.12 (§1.5.1). ↩