internal/decimal_kernel design
Design goal
decimal and decimal_gda implement two different standards on top of the
same arithmetic: nonnegative integers in decimal digits. The integer part
should exist once, so that a fix or a measurement helps both, while nothing of
either standard leaks into it. The package therefore contains only functions
from integers to integers.
Mathematical background
A coefficient is stored in base , the largest power of
ten below , so a limb product is below and
fits a UInt64 together with carries. Values below (two limbs) are
kept as one UInt64. Digit counts, trailing zeros, the half-unit comparison
and the last-digit test of ZeroFiveUp are then limb operations; no
binary-to-decimal conversion exists.
Every operation computes an exact result:
- , for , ;
- with and ;
- and , which is everything a rounding decision needs;
- , the multiplicity of a unit factor and exact division by a unit.
Because each result is determined by the mathematical definition, the algorithm chosen by the dispatcher (schoolbook, Karatsuba, Toom-3, a two-prime NTT, Knuth’s Algorithm D, Burnikel–Ziegler, Newton reciprocal division) cannot change a value. The dispatch is performance policy.
The NTT bound
The NTT uses base- digits and the primes and
, so . A
convolution coefficient is a sum of at most products of
digits at most , hence at most , and the Chinese
remainder theorem recovers it exactly when that is below , that is for
. Both primes have -th roots of unity, so the
transform length is at most and :
. The bound
holds for every length the transform accepts, and dec_coeff_ntt_limits_fit
checks it before each use. (decimal used base- digits before the
kernels were shared; the bound was also satisfied, and
the product is the same integer either way.)
Design decisions
One kernel, two representations merged
The two packages had diverged. decimal_gda stored Small(UInt64) and had
small-value fast paths, a numerator-aware division dispatch and an
allocation-free scaled comparison; decimal stored an inline UInt32, had
gcd, mod, shift_power10_mod and a whole-limb mode in trim. The shared
kernel is the union, built on the Small(UInt64) representation, because the
fast paths are pure integer facts. The functions that only one side had are
kept (they are exact integer functions too). The trim whole-limb mode counts
trailing zeros per limb instead of per digit and returns the same count as the
digit loop; dec_coeff_count_factor_unit_repr returns early when the lowest
limb is not divisible by 2 or 5 (the base is divisible by both, so the lowest
limb decides), which is cheaper than the batched attempt for the common case.
Rounding decisions as pure functions
A rounding decision is a function of a coefficient and the digits that were discarded: given , the remainder with , the sign and the direction, the kept magnitude is incremented when
The kernel computes this from dec_coeff_div_pow10_round_info_repr or a
division, in a DecCoeffRounding enum that carries the direction only. What the
direction is applied to (the precision, the exponent range, the tininess rule,
the flags raised by the discarded digits) is decided by the finalizer of each
package, which converts its own rounding mode with one total match. The kernel
therefore needs neither package’s mode, context nor flags type.
What stays out
Nothing that depends on a standard moves here: rounding modes, precision,
exponent range, the finalizer, flags, traps, the Decimal type, the DPD and
BID codecs. The design page of decimal_gda explains why those must not be
shared. A function belongs in the kernel only if it would be correct, with the
same meaning, in either standard.
Public types, internal package
DecCoeff and DecCoeffRounding are pub(all) so that the two packages can
pattern-match the Small case in their own fast paths without a call per
access; SignedDecCoeff is pub, so its fields can be read but only this
package builds one. The algorithm enums, the scratch types and the helpers
that no other package uses are private: the package keeps public only what
decimal, decimal_gda or their tests name. Visibility is also bounded by the
package itself: internal/ makes it unimportable outside Luna-Flow/floating,
and no public signature of decimal or decimal_gda mentions the types.
Option-free hot paths
dec_coeff_small_value returns an Option, which allocates for a small
value. Functions on the hot path of the decimal greatest-common-divisor loop
(dec_coeff_mod_repr) match the constructors directly instead. A paired A/B of
decimal division at 34 and 100 digits showed the allocation; matching
removed it.
Digit counts, accumulators and exact quotients
dec_coeff_small_digits counts the digits of a one-word value with the
leading-zero count (floor(bits * 1233 / 4096) is the digit count or one
less) and one comparison with a power of ten; value | 1 maps zero to one
digit and never changes the count of another value. Both packages use it, as
digits10 of every Small coefficient. dec_coeff_from_unit_accumulator
trims leading zero limbs and truncates the buffer in one step and does not scan
the limbs for values at or above the base: every producer writes limbs below
the base, which the white-box test “unit accumulator producers write limbs
below the base” checks over shifts, sums, products and quotients. A division
that must also say whether the exact quotient has a finite decimal expansion
uses dec_coeff_round_div_expansion: with , prime to 10,
the expansion of is finite exactly when , and as 10 is
invertible modulo that is equivalent to dividing the remainder of
by , so the one division that produces the quotient also decides
it.
Integer square root
dec_coeff_integer_sqrt_rem_repr returns the floor root of and the
remainder . A value below takes the hardware root of the
nearest double, which is within one of the answer, and two comparisons with
exact word products settle it. A longer value of digits is split as
with and . The root
of comes from the same function one level down, and
never lies below : and
. Newton’s step
started at or above
decreases to and never falls below it, so the start needs no estimate and
the working size doubles from the bottom of the recursion. The earlier version
began at a power of ten and ran every step at full size, about
divisions of a -digit number. The division of each step also ends the loop:
for the quotient reaches exactly when
, and then gives the remainder with
(because ), so the squaring that the
earlier version needed for the remainder is gone. The pair is
unique, so no caller can observe the change; the white-box test compares it bit
for bit with the previous implementation, kept in the test file, on random
operands of 1 to 112 limbs, perfect squares and their neighbours, and powers of
ten.
Rounding a limb coefficient in one pass
dec_coeff_round_div_pow10 shifts a coefficient of digits right by
digits and rounds. Write . The rounding digit is the digit at
position and the sticky information is whether anything below it is
nonzero; both are read from limb and, only while that
limb’s lower part is zero, from the limbs below it (the scan ends at the first
nonzero limb). Limb of the quotient is then
,
one division by per source limb, written to a new array of exactly
limbs, so that no trimming and no digit count is
needed afterwards. The increment is applied to that array in place: it carries
from limb 0 up to the first limb that is not , and appends a limb only
if every limb carried. The digit count of the result is taken from its top
limb. The earlier version copied the coefficient, shifted the copy, trimmed it
and counted its digits, scanned the source again for the rounding digits, and
added the unit through a second copy, a pass and a second digit count: four
allocations and about five passes against one allocation (plus the Limbs
box) and one pass.
dec_coeff_round_div_pow10_owned is the same function for a caller that owns
the limb array: the shift writes behind its own reads (limb of the result
is stored after limb of the source was loaded, and ), so the
array is rounded in place and truncated, and becomes the limbs of the result.
Values of two limbs or fewer are always below and are Small. The
white-box test compares both entries with the previous implementation, kept
in the test file, bit for bit.
dec_coeff_round_accumulator is the entry for a producer that owns a fresh
accumulator: the aligned sum of an addition forms its limbs in an array that
nothing else sees. The caller reads the digit count
(dec_coeff_accumulator_digits) and whether the digits to discard contain a
nonzero one (dec_coeff_accumulator_discards_nonzero, a read of the array
only) and then rounds in place; each call returns one scalar or the coefficient,
so the path allocates no tuple (a returned tuple allocates on the native
backend on every call), and the caller builds the flags without a second pass.
The same release removed an allocation per carrying limb from
dec_coeff_unit_add_sub: the helper that split a carry into a digit and the
next carry returned a tuple and is now two scalar expressions.
For a coefficient that the caller does not own (a product or a quotient that
may be shared), dec_coeff_round_pow10_coeff is the same one-pass rounding into
a new array and dec_coeff_discards_nonzero reads the discarded digits only;
both return one scalar or coefficient and allocate no tuple.
Division and the product without scratch objects
Knuth’s algorithm D divides the normalized numerator in place: the numerator
and the divisor are multiplied by into two
FixedArray[UInt64] scratch arrays, each quotient limb is estimated from the
top two limbs and the second limb of the divisor, corrected, and the product by
the divisor is subtracted in place with a borrow; the quotient limbs go straight
into the Array[UInt32] that becomes the result. The remainder is the
normalized remainder divided by the normalization unit, which divides it
exactly, so the old branch that multiplied the quotient back and corrected it
was never taken and is gone (an abort now guards the invariant). The caller that
needs only “the remainder is zero” reads the scratch array and builds nothing.
dec_coeff_div_scaled_inexact is the division behind decimal_gda’s divide:
the dividend is formed (a whole-limb shift and one multiplication
by ) and normalized in the scratch array; with the remainder
nonzero the exact quotient has a finite expansion iff the part of the divisor
prime to 10 divides the remainder, and the valuations of 2 and 5 of the divisor,
when below 9, are those of its lowest limb, so a divisor prime to 10 (the usual
case) is decided with no division at all ( divisor), and others
need one division by a unit and a remainder test of a quotient of at most a few
limbs. The schoolbook product reads the limbs of a Limbs value in place
(a Small has two at most), accumulates by columns up to 18 limbs and by rows
beyond, and stores limbs below the base into the result array directly.
The schoolbook product and square in column order
Column of a product is and each term is at most
with . The sum of a column is accumulated in one
UInt64 that starts at the carry of the previous column; after every 16
terms it is folded, , , and
is added to a second counter, so that after a fold . Between two folds
,
and at the start of a column (no fold yet, = carry)
holds as long as
. The carry out of a column with terms is
at most ; the
result array has limbs, so and,
by induction on the columns, : the accumulator
cannot overflow for any operand the function can receive. When the shorter
operand has at most 18 limbs no column has more than 18 terms, nothing needs to
fold, every carry is below and a column sum is below
(margin
). That case is its own function, the loop of the former
column branch, on purpose: the grouped loop, with a fold count of 18 as well as
16, or a plain while loop, makes the compiler emit a vectorized loop whose
set-up costs 4 to 11 percent on columns of 16 to 18 terms (measured on 4, 12,
16, 17 and 18 limbs), and the counting loop for i in a..<=b stays scalar and
is the fastest below 19 limbs; longer operands fold every 16 terms as above. The loop
has no stores inside and reads the limbs of a Limbs value in place, which
lets the compiler keep both buffer pointers in registers and vectorize the
groups of 16 (a variant that copied the operands to FixedArray was measured
and was not faster).
The square sums the cross terms , , once, in the same groups (starting at 0, so sixteen of them are below ), folds, and doubles the two parts afterwards: the column value is (below ) and the carry out is . A doubled term would be below and only 9 of them would fit a word; doubling after the sum keeps 16 per fold. With at most cross terms per column and the carry stays below as for the product.
With the faster loops the Karatsuba thresholds of the native build were measured again (instructions per call, one level against the schoolbook product at the same size, repetition counts large enough that two runs agree to 0.2 percent): the product costs 232,302 (schoolbook) against 241,489 at 160 limbs, 332,354 against 326,978 at 192 and 450,385 against 425,681 at 224, so it crosses near 180 limbs; the square costs 458,323 against 470,582 at 320 limbs, 552,045 against 551,981 at 352 and 654,450 against 639,024 at 384, so it crosses at 352. The thresholds are now 192 and 352 (they were 96 and 48). The other targets keep theirs, which were measured against the former loops and are stale; each of their threshold files says so and they are not measured again here. The repetition counts matter: an instruction count per call is the difference of two counts divided by the difference, and a difference of only 15 million instructions (about 100 calls of a 128-limb product) varied by 18 percent between two runs from the one-time costs of the allocator (page faults counted as instructions); with a difference of at least 800 million two runs agree to 0.2 percent.
has_finite_decimal_expansion_repr(numerator, denominator) answers whether
has a finite decimal expansion without a gcd. Let with
prime to 10. In lowest terms the quotient has the denominator
, and that has no prime other than 2 and 5 exactly when the gcd
takes every prime of out, i.e. when ( is coprime to the
factors 2 and 5 of ). So the quotient is finite iff . The
valuations of 2 and 5 are those of the lowest limb when both are below 9
( is divisible by and ); then is one
division by a unit, and for prime to 10 the test is . Otherwise
the factors are removed by division. dec_coeff_div_scaled_inexact uses the
same unit for the remainder of its division. The white-box test compares the
decision with the previous implementation and with the decision of the gcd
route on divisors with factors 2 and 5 of valuation up to 37 and 25 (the lowest
limb zero), multiples and non-multiples of , and 1 to 120 limbs.
Correctness and invariants
- Canonical form. A
Limbsvalue has no leading zero limb and is at least ; a smaller value isSmall. Equal integers therefore have equal representations, andDecCoeff::to_stringis the plain decimal string. - Persistence. No operation mutates the limbs of an operand.
- Totality inside the contract. A violated precondition aborts; it is never mapped to a value.
- Exactness. All results equal the
BigIntresult. The white-box tests compare withBigIntat limb boundaries, at the threshold of every target and for forced algorithms on nines, powers of ten and sparse operands.
Trade-offs and limitations
Sharing means a performance change hits both standards; every change is
measured on both. The kernel is not a general bignum: it has no negative
numbers except SignedDecCoeff for intermediate values, and no radix other
than .
References
D. E. Knuth, The Art of Computer Programming, vol. 2, 3rd ed., §4.3.1; C. Burnikel and J. Ziegler, “Fast recursive division”, MPI-I-98-1-022, 1998; R. Brent and P. Zimmermann, Modern Computer Arithmetic, Cambridge 2010, §1.3–1.4 and §2.4.