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 c≥0c \ge 0 is stored in base B=109B = 10^{9}, the largest power of ten below 2302^{30}, so a limb product is below B2=1018<260B^{2} = 10^{18} < 2^{60} and fits a UInt64 together with carries. Values below 101810^{18} (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:

  • add⁡(a,b)=a+b\operatorname{add}(a,b) = a + b, sub⁡(a,b)=a−b\operatorname{sub}(a,b) = a - b for a≥ba \ge b, mul⁡(a,b)=ab\operatorname{mul}(a,b) = ab;
  • divrem⁡(a,b)=(q,r)\operatorname{divrem}(a,b) = (q,r) with a=qb+ra = qb + r and 0≤r<b0 \le r < b;
  • shift⁡(a,k)=a⋅10k\operatorname{shift}(a,k) = a\cdot 10^{k} and divpow10⁡(a,k)=(⌊a/10k⌋,  a mod 10k≠0,  sign⁡(2(a mod 10k)−10k))\operatorname{divpow10}(a,k) = (\lfloor a/10^{k}\rfloor,\; a \bmod 10^{k} \ne 0,\; \operatorname{sign}(2(a \bmod 10^{k}) - 10^{k})), which is everything a rounding decision needs;
  • gcd⁡\operatorname{gcd}, 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-10510^5 digits and the primes p1=998 244 353p_1 = 998\,244\,353 and p2=754 974 721p_2 = 754\,974\,721, so p1p2=753 649 251 896 000 513p_1 p_2 = 753\,649\,251\,896\,000\,513. A convolution coefficient is a sum of at most m=min⁡(na,nb)m = \min(n_a, n_b) products of digits at most 99 99999\,999, hence at most m⋅99 9992m\cdot 99\,999^{2}, and the Chinese remainder theorem recovers it exactly when that is below p1p2p_1p_2, that is for m<75 366 432m < 75\,366\,432. Both primes have 2232^{23}-th roots of unity, so the transform length is at most 2232^{23} and m≤222m \le 2^{22}: 222⋅99 9992=41 942 201 143 394 304<p1p22^{22}\cdot 99\,999^{2} = 41\,942\,201\,143\,394\,304 < p_1 p_2. The bound holds for every length the transform accepts, and dec_coeff_ntt_limits_fit checks it before each use. (decimal used base-10410^4 digits before the kernels were shared; the bound 222⋅9 99922^{22}\cdot 9\,999^{2} 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 qq, the remainder rr with 0≤r<d0 \le r < d, the sign and the direction, the kept magnitude is incremented when

{neverDown,always (if r>0)Up,sign⁡=+Ceiling,sign⁡=−Floor,2r>d∨(2r=d∧q odd)HalfEven,2r≥dHalfUp,2r>dHalfDown,q mod 10∈{0,5}ZeroFiveUp.\begin{cases} \text{never} & \text{Down},\\ \text{always (if } r > 0) & \text{Up},\\ \operatorname{sign} = + & \text{Ceiling},\\ \operatorname{sign} = - & \text{Floor},\\ 2r > d \lor (2r = d \land q \text{ odd}) & \text{HalfEven},\\ 2r \ge d & \text{HalfUp},\\ 2r > d & \text{HalfDown},\\ q \bmod 10 \in \{0, 5\} & \text{ZeroFiveUp}. \end{cases}

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 d=2a5bud = 2^a 5^b u, uu prime to 10, the expansion of n/dn/d is finite exactly when u∣nu \mid n, and as 10 is invertible modulo uu that is equivalent to uu dividing the remainder of n 10kn\,10^k by dd, so the one division that produces the quotient also decides it.

Integer square root

dec_coeff_integer_sqrt_rem_repr returns the floor root ss of nn and the remainder n−s2n - s^2. A value below 101810^{18} 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 DD digits is split as n=h 102t+ln = h\,10^{2t} + l with t≈D/4t \approx D/4 and 0≤l<102t0 \le l < 10^{2t}. The root shs_h of hh comes from the same function one level down, and x0=(sh+1) 10tx_0 = (s_h + 1)\,10^{t} never lies below ss: n<(h+1) 102tn < (h+1)\,10^{2t} and h+1≤(sh+1)2h + 1 \le (s_h+1)^2. Newton’s step x↦⌊(x+⌊n/x⌋)/2⌋x \mapsto \lfloor (x + \lfloor n/x \rfloor)/2 \rfloor started at or above ss decreases to ss 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 log⁡2D+2\log_2 D + 2 divisions of a DD-digit number. The division of each step also ends the loop: for x≥sx \ge s the quotient q=⌊n/x⌋q = \lfloor n/x \rfloor reaches xx exactly when x=sx = s, and then n=xq+rn = xq + r gives the remainder r+x(q−x)r + x(q - x) with q−x∈{0,1,2}q - x \in \{0, 1, 2\} (because n<(x+1)2n < (x+1)^2), so the squaring that the earlier version needed for the remainder is gone. The pair (s,n−s2)(s, n - s^2) 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 DD digits right by kk digits and rounds. Write k=9u+ck = 9u + c. The rounding digit is the digit at position k−1k - 1 and the sticky information is whether anything below it is nonzero; both are read from limb ⌊(k−1)/9⌋\lfloor (k-1)/9 \rfloor and, only while that limb’s lower part is zero, from the limbs below it (the scan ends at the first nonzero limb). Limb jj of the quotient is then ⌊au+j/10c⌋+(au+j+1 mod 10c)⋅109−c\lfloor a_{u+j} / 10^{c} \rfloor + (a_{u+j+1} \bmod 10^{c})\cdot 10^{9-c}, one division by 10c10^{c} per source limb, written to a new array of exactly ⌈(D−k)/9⌉\lceil (D-k)/9 \rceil 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 109−110^{9}-1, 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 jj of the result is stored after limb j+1j+1 of the source was loaded, and j≤u+jj \le u + j), 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 101810^{18} 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 ⌊B/(vn−1+1)⌋\lfloor B/(v_{n-1}+1) \rfloor 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 c⋅10sc\cdot 10^{s} is formed (a whole-limb shift and one multiplication by 10s mod 910^{s \bmod 9}) and normalized in the scratch array; with the remainder nonzero the exact quotient has a finite expansion iff the part uu 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 (0<r<u=0 < r < u = 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 cc of a product is ∑iaibc−i\sum_i a_i b_{c-i} and each term is at most (B−1)2<1018(B-1)^2 < 10^{18} with B=109B = 10^9. The sum of a column is accumulated in one UInt64 ss that starts at the carry of the previous column; after every 16 terms it is folded, q=⌊s/B⌋q = \lfloor s/B \rfloor, s←s−qBs \leftarrow s - qB, and qq is added to a second counter, so that after a fold s<Bs < B. Between two folds s<B+16 (B−1)2<1.6⋅1019+109<264≈1.8447⋅1019s < B + 16\,(B-1)^2 < 1.6\cdot 10^{19} + 10^{9} < 2^{64} \approx 1.8447\cdot 10^{19}, and at the start of a column (no fold yet, ss = carry) carry+16 (B−1)2<264\text{carry} + 16\,(B-1)^2 < 2^{64} holds as long as carry<2.44⋅1018\text{carry} < 2.44\cdot 10^{18}. The carry out of a column with nn terms is at most ⌊(carry+n (B−1)2)/B⌋<carry/B+nB\lfloor (\text{carry} + n\,(B-1)^2)/B \rfloor < \text{carry}/B + nB; the result array has ℓa+ℓb+1<231\ell_a + \ell_b + 1 < 2^{31} limbs, so n≤min⁡(ℓa,ℓb)<230n \le \min(\ell_a, \ell_b) < 2^{30} and, by induction on the columns, carry<1.08⋅1018\text{carry} < 1.08\cdot 10^{18}: 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 1.9⋅10101.9\cdot 10^{10} and a column sum is below 1.9⋅1010+18 (B−1)2<1.8000000019⋅1019<2641.9\cdot 10^{10} + 18\,(B-1)^2 < 1.8000000019\cdot 10^{19} < 2^{64} (margin 4.4⋅10174.4\cdot 10^{17}). 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 aiac−ia_i a_{c-i}, i<c−ii < c - i, once, in the same groups (starting at 0, so sixteen of them are below 1.6⋅10191.6\cdot 10^{19}), folds, and doubles the two parts afterwards: the column value is carry+ac/22+2s\text{carry} + a_{c/2}^2 + 2s (below carry+1018+2⋅109\text{carry} + 10^{18} + 2\cdot 10^{9}) and the carry out is ⌊value/B⌋+2qtotal\lfloor \text{value}/B \rfloor + 2q_{\text{total}}. A doubled term would be below 2⋅10182\cdot 10^{18} and only 9 of them would fit a word; doubling after the sum keeps 16 per fold. With at most ℓ/2<229\ell/2 < 2^{29} cross terms per column 2qtotal<230B2q_{\text{total}} < 2^{30} B and the carry stays below 1.08⋅10181.08\cdot 10^{18} 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 N/DN/D has a finite decimal expansion without a gcd. Let D=2a5buD = 2^{a}5^{b}u with uu prime to 10. In lowest terms the quotient has the denominator D/gcd⁡(N,D)D/\gcd(N, D), and that has no prime other than 2 and 5 exactly when the gcd takes every prime of uu out, i.e. when u∣Nu \mid N (uu is coprime to the factors 2 and 5 of DD). So the quotient is finite iff u∣Nu \mid N. The valuations of 2 and 5 are those of the lowest limb when both are below 9 (10910^{9} is divisible by 292^{9} and 595^{9}); then u=D/2a5bu = D/2^{a}5^{b} is one division by a unit, and for DD prime to 10 the test is D∣ND \mid N. 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 uu, and 1 to 120 limbs.

Correctness and invariants

  • Canonical form. A Limbs value has no leading zero limb and is at least 101810^{18}; a smaller value is Small. Equal integers therefore have equal representations, and DecCoeff::to_string is 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 BigInt result. The white-box tests compare with BigInt at 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 10910^{9}.

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.