decimal_gda design

This page explains the mathematics that decimal_gda implements and why the package is built the way it is. The tutorial shows how to use it and the API page lists every name.

Design goal

decimal_gda implements the General Decimal Arithmetic Specification (version 1.70) by M. F. Cowlishaw11 M. F. Cowlishaw, General Decimal Arithmetic Specification, version 1.70 (2009), https://speleotrove.com/decimal/decarith.html. The test suite is the same author’s dectest collection, version 2.62. as pure MoonBit values. A GDA operation is specified to produce more than a number: it produces a result, a set of conditions, an update of the flags of the context, and possibly a trap that transfers control while the defined result stays available. The goal is to model all of that exactly and observably, so that

  • each operation is a total function from (operands, context) to (result, raised conditions, next context, trap decision), with no hidden state;
  • results are bit-for-bit those of the specification, checked against the pinned official test suite (see conformance);
  • the package is independent of the IEEE 754 package decimal, so changes to one contract cannot leak into the other.

Mathematical background

Numbers, cohorts and the adjusted exponent

A finite number of GDA is a triple (s,c,q)(s, c, q) with sign s∈{0,1}s \in \{0, 1\}, coefficient c∈Nc \in \mathbb{N} and exponent q∈Zq \in \mathbb{Z}, denoting

v(s,c,q)=(−1)s⋅c⋅10q.v(s, c, q) = (-1)^s \cdot c \cdot 10^{q}.

The map vv is not injective: (0,250,−2)(0, 250, -2) and (0,25,−1)(0, 25, -1) both denote 2.52.5. The triples with the same value form a cohort. GDA keeps the triple, not only the value, because the exponent carries meaning: it gives the quantum 10q10^q, and “2.50” was measured to the cent. Zero is signed, so (1,0,q)(1, 0, q) is −0-0. For c>0c > 0 write d(c)d(c) for the number of decimal digits of cc and

q^=q+d(c)−1\hat q = q + d(c) - 1

for the adjusted exponent, the exponent of the leading digit: 10q^≤∣v∣<10q^+110^{\hat q} \le |v| < 10^{\hat q + 1}. Besides finite numbers there are the special values ±∞\pm\infty and the quiet and signaling NaNs, which carry a sign and a payload cc.

Contexts and the representable set

A context fixes a precision p≥1p \ge 1, a rounding, an exponent range Emin⁡≤Emax⁡E_{\min} \le E_{\max} and a clamp bit. A finite number is representable in the context when

d(c)≤p,q^≤Emax⁡,q≥Etiny   where   Etiny=Emin⁡−p+1,d(c) \le p, \qquad \hat q \le E_{\max}, \qquad q \ge E_{\mathrm{tiny}} \;\text{ where }\; E_{\mathrm{tiny}} = E_{\min} - p + 1,

and, if clamping is on, also q≤Etop=Emax⁡−p+1q \le E_{\mathrm{top}} = E_{\max} - p + 1.

The value EtinyE_{\mathrm{tiny}} is the exponent of the smallest unit. A number with q^=Emin⁡\hat q = E_{\min} and pp digits has q=Emin⁡−p+1q = E_{\min} - p + 1, and numbers below 10Emin⁡10^{E_{\min}} (the subnormal range) keep that unit while losing leading digits. The value EtopE_{\mathrm{top}} is the exponent of the largest pp-digit number with q^=Emax⁡\hat q = E_{\max}. Clamping makes the set of exponents exactly the one an IEEE interchange format can encode, which is why the decimal32, decimal64 and decimal128 presets clamp.

The arithmetic rule: exact result, then round once

Every arithmetic operation in GDA is defined by the same two-step rule:

  1. compute the exact mathematical result xx and choose, among the triples that denote xx, the one whose exponent is closest to the operation’s ideal exponent q∗q^\ast;
  2. if that triple is not representable, round it to the context, raising conditions that describe what happened.

Step 1 is exact, so step 2 is a single rounding, and every bound below is a bound on one rounding.

The package follows the rule literally. Each operation builds an exact coefficient and exponent from its operands and then calls one shared finalizer (in the source: normalize_decimal_parts_ctx_repr followed by finalize_finite_ctx). The finalizer is the only code that rounds a finite result or raises a condition related to precision or range.

Ideal exponents

The ideal exponent is the coarsest quantum that represents the exact result using only information present in the operands. Write the operands as x1=c110q1x_1 = c_1 10^{q_1} and x2=c210q2x_2 = c_2 10^{q_2}, and the operand of the square root as x=c 10qx = c\,10^{q}, leaving signs aside. Let qmin⁡q_{\min} be the smaller of the two exponents, min⁡(q1,q2)\min(q_1, q_2). The derivations are short:

x1±x2=(c110q1−qmin⁡±c210q2−qmin⁡)10qmin⁡,qmin⁡=min⁡(q1,q2),x1×x2=(c1c2) 10q1+q2,x1÷x2=c1c2 10q1−q2,x=c 10q−2⌊q/2⌋  10⌊q/2⌋.\begin{aligned} x_1 \pm x_2 &= \bigl(c_1 10^{q_1 - q_{\min}} \pm c_2 10^{q_2 - q_{\min}}\bigr) 10^{q_{\min}}, & q_{\min} &= \min(q_1, q_2),\\ x_1 \times x_2 &= (c_1 c_2)\, 10^{q_1 + q_2}, & &\\ x_1 \div x_2 &= \frac{c_1}{c_2}\, 10^{q_1 - q_2}, & &\\ \sqrt{x} &= \sqrt{c\,10^{q - 2\lfloor q/2 \rfloor}}\;10^{\lfloor q/2 \rfloor}. & & \end{aligned}

For addition, qmin⁡q_{\min} is the largest exponent at which both operands have an integer coefficient. It is therefore the largest exponent at which the sum is guaranteed to be an integer multiple of the quantum, and the bracket is then an exact integer coefficient. For multiplication the coefficient c1c2c_1 c_2 is an integer at exponent q1+q2q_1 + q_2 and in general at no larger one. For division the quotient c1/c2c_1 / c_2 need not be an integer, so the ideal q1−q2q_1 - q_2 is used only when it is reachable. The exact quotient is written with the exponent nearest to q1−q2q_1 - q_2 that keeps an integer coefficient of at most pp digits, and an inexact quotient uses all pp digits. For the square root, ⌊q/2⌋\lfloor q/2 \rfloor is the exponent of the root whose square has the largest even exponent not above qq, namely 2⌊q/2⌋2\lfloor q/2 \rfloor.

The table lists the ideal exponent q∗q^\ast of each operation. In it, nn is the integer operand of scaleb and of an integer power, and kk is an integer.

OperationIdeal exponent q∗q^\ast
add, subtract, fma (sum part)qmin⁡q_{\min}
multiply, fma (product part)q1+q2q_1 + q_2
divideq1−q2q_1 - q_2 if exact, else pp digits
sqrt⌊q/2⌋\lfloor q/2 \rfloor if exact, else pp digits
remainder, remainder_nearqmin⁡q_{\min}
divide_integer, to_integral_*max⁡(q,0)\max(q, 0) for the integral value, 0 for a quotient
quantize, rescalethe requested exponent
scalebq+nq + n
power with integer nn, exactnqn q
exp, ln, log10, non-integer powerpp digits (always inexact, except exp(0), ln(1), log10(10^k))
plus, minus, abs, applyqq

A zero result has no leading digit, so its exponent is simply the ideal one, clamped into [Etiny,Emax⁡][E_{\mathrm{tiny}}, E_{\max}], or into [Etiny,Etop][E_{\mathrm{tiny}}, E_{\mathrm{top}}] under clamping. For a zero, quantize and rescale follow the rule too: the requested exponent must be at most Emax⁡E_{\max}, and under clamp one above EtopE_{\mathrm{top}} is folded down to it with clamped, as decNumber’s decQuantizeOp does by calling decFinalize for a zero.

For a zero quotient, divide_integer builds the zero at the ideal exponent 0 and then passes it to the shared finalizer. The zero keeps the sign of the quotient, and clamping can fold the exponent down without the change of an exact zero’s exponent counting as rounding.

The sign of an exact zero sum is ++ unless both operands are negative, or the rounding is Floor and either operand is negative (GDA 1.70, page 24 (Arithmetic operations)). This is the decimal form of the rule of IEEE 754-2019 6.3 that x−x=+0x - x = +0 except when rounding towards −∞-\infty.

///|
test "ideal exponents" {
  let ctx = @decimal_gda.GdaContext::decimal64()
  let d = (s : String) => @decimal_gda.Decimal::from_string(s).unwrap()
  inspect(@decimal_gda.add(d("1.30"), d("1.2"), ctx).value(), content="2.50")
  inspect(@decimal_gda.multiply(d("1.30"), d("1.2"), ctx).value(), content="1.560")
  inspect(@decimal_gda.divide(d("2.40"), d("2"), ctx).value(), content="1.20")
  inspect(@decimal_gda.divide(d("1"), d("4"), ctx).value(), content="0.25")
  inspect(@decimal_gda.sqrt(d("1.00"), ctx).value(), content="1.0")
  inspect(@decimal_gda.subtract(d("1.0"), d("1.00"), ctx).value(), content="0.00")
}

Rounding to precision

Rounding shortens the coefficient of an exact result to the pp digits of the context’s precision. Let the exact result be x=(−1)sc 10qx = (-1)^s c\,10^{q}, with sign ss, coefficient cc and exponent qq, and let d(c)=p+kd(c) = p + k with k≥1k \ge 1, where d(c)d(c) is the number of decimal digits of cc. Divide off the kk low digits, c=h 10k+rc = h\,10^{k} + r with 0≤r<10k0 \le r < 10^k, so that hh is the retained head and rr the discarded tail. Each of the eight rounding algorithms (GDA 1.70, pages 13 and 14 (Abstract representation of context)) returns x^=(−1)s(h+δ) 10q+k\hat x = (-1)^s (h + \delta)\,10^{q+k} with an increment δ∈{0,1}\delta \in \{0, 1\}, and the eight differ only in δ\delta (in the source: should_increment_decimal_repr). Below, [P][P] is 1 when the condition PP holds and 0 otherwise:

δDown=0,δUp=[r>0],δCeiling=[r>0∧s=0],δFloor=[r>0∧s=1],δHalfUp=[2r≥10k],δHalfDown=[2r>10k],δHalfEven=[2r>10k∨(2r=10k∧h odd)],δZeroFiveUp=[r>0∧h≡0(mod5)].\begin{aligned} \delta_{\mathrm{Down}} &= 0, & \delta_{\mathrm{Up}} &= [r > 0],\\ \delta_{\mathrm{Ceiling}} &= [r > 0 \wedge s = 0], & \delta_{\mathrm{Floor}} &= [r > 0 \wedge s = 1],\\ \delta_{\mathrm{HalfUp}} &= [2r \ge 10^k], & \delta_{\mathrm{HalfDown}} &= [2r > 10^k],\\ \delta_{\mathrm{HalfEven}} &= [2r > 10^k \vee (2r = 10^k \wedge h \text{ odd})], & \delta_{\mathrm{ZeroFiveUp}} &= [r > 0 \wedge h \equiv 0 \pmod 5]. \end{aligned}

The algorithm ZeroFiveUp reads “round towards zero, unless the retained last digit is 0 or 5”. After it, a last digit of 0 or 5 means the rounding was exact, and any other last digit after an inexact rounding is never 0 or 5. Rounding the result again to at least one digit fewer, in any rounding algorithm, therefore gives the same value as rounding the exact result once in that algorithm (GDA 1.70, page 14 (Abstract representation of context), note 17, states this use). The retained last digit acts as a sticky digit: when something nonzero was discarded, it is moved off 0 and 5, the values at which a later rounding tests the discarded part against zero or half. Round-to-odd does the same in binary.

The comparison 2r2r versus 10k10^k is done exactly on the decimal limbs of the coefficient (in the source: dec_coeff_div_pow10_round_info_repr returns the quotient, whether r>0r > 0, and the sign of 2r−10k2r - 10^k). If h+δ=10ph + \delta = 10^p, the rounded coefficient has p+1p + 1 digits; its last digit, a zero, is dropped and the result is 10p−1⋅10q+k+110^{p-1} \cdot 10^{q+k+1} (GDA 1.70, page 14 (Abstract representation of context)). Before rounding, the finalizer first reduces cc by dropping its trailing zeros; when the exact coefficient is too long only because of zeros, the result is exact and only Rounded is raised.

Let u=10q+ku = 10^{q+k} be the unit in the last place of the result x^\hat x. Since x^−x=(−1)s(δ 10k−r) 10q\hat x - x = (-1)^s(\delta\,10^k - r)\,10^{q}, and since ∣δ 10k−r∣≤10k/2|\delta\,10^k - r| \le 10^k/2 for the half-way algorithms (HalfUp, HalfDown, HalfEven) and <10k< 10^k for the directed algorithms (Down, Up, Ceiling, Floor) and for ZeroFiveUp,

∣x^−x∣≤12u    (half-way algorithms),∣x^−x∣<u    (directed algorithms and ZeroFiveUp),|\hat x - x| \le \tfrac12 u \;\;(\text{half-way algorithms}), \qquad |\hat x - x| < u \;\;(\text{directed algorithms and } \mathtt{ZeroFiveUp}),

and since c≥10p+k−1c \ge 10^{p+k-1} gives ∣x∣≥10p−1u|x| \ge 10^{p-1} u,

∣x^−x∣∣x∣≤12 101−p    (half-way algorithms),∣x^−x∣∣x∣<101−p    (directed algorithms and ZeroFiveUp).\frac{|\hat x - x|}{|x|} \le \tfrac12\,10^{1-p} \;\;(\text{half-way algorithms}), \qquad \frac{|\hat x - x|}{|x|} < 10^{1-p} \;\;(\text{directed algorithms and } \mathtt{ZeroFiveUp}).

The bound 12101−p\frac12 10^{1-p} is the decimal unit roundoff u\mathbf u of the standard model fl(x∘y)=(x∘y)(1+ε)\mathrm{fl}(x \circ y) = (x \circ y)(1 + \varepsilon), ∣ε∣≤u|\varepsilon| \le \mathbf u, in which ∘\circ is an arithmetic operation, fl\mathrm{fl} its rounded result and ε\varepsilon the relative error.22 N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM 2002, section 2.2. Decimal wobble is larger than binary: the relative spacing varies by a factor of 10 across a decade, against 2 in binary (Goldberg 1991, section 1.2). Rounding raises Rounded whenever k≥1k \ge 1 digits are removed and Inexact whenever a removed digit was nonzero (r>0r > 0).

The full proofs of this bound and of the other rounding facts on this page are in the attachment:

Rounding proofs for decimal_gda

Subnormal results and EtinyE_{\mathrm{tiny}}

Let Emin⁡E_{\min} be the least adjusted exponent of a normal number in the context, and Etiny=Emin⁡−p+1E_{\mathrm{tiny}} = E_{\min} - p + 1 the least exponent a result may have (GDA 1.70, page 11 (Normal numbers, subnormal numbers and Underflow)). If the exact result has q^<Emin⁡\hat q < E_{\min}, where q^=q+d(c)−1\hat q = q + d(c) - 1 is its adjusted exponent, it is tiny. A tiny result may still need the unit 10Etiny10^{E_{\mathrm{tiny}}} at most, so the rounding position is not “keep pp digits” but “keep the digits at or above 10Etiny10^{E_{\mathrm{tiny}}}”. With an exact coefficient of DD digits and exponent qq, rounding to pp digits would give the exponent q+max⁡(0,D−p)q + \max(0, D - p); when that is below EtinyE_{\mathrm{tiny}} the finalizer instead removes k=Etiny−qk = E_{\mathrm{tiny}} - q digits, possibly all of them, in one rounding.

A longer coefficient whose exponent is below EtinyE_{\mathrm{tiny}} but whose magnitude is normal is rounded once to pp digits; rounding it to the subnormal grid first would round twice. In decimal32 (p=7p = 7, Emin⁡=−95E_{\min} = -95), 3.000001⋅10−45×1.500001⋅10−453.000001\cdot 10^{-45} \times 1.500001\cdot 10^{-45} is 4.500005E-90.

The absolute error is then bounded by the subnormal unit,

∣x^−x∣≤12 10Etiny    (half-way algorithms),|\hat x - x| \le \tfrac12\,10^{E_{\mathrm{tiny}}} \;\;(\text{half-way algorithms}),

but the relative error is not bounded by u\mathbf u any more: the precision of the value falls gradually from pp digits to 1 as ∣x∣|x| drops from 10Emin⁡10^{E_{\min}} to 10Etiny10^{E_{\mathrm{tiny}}}.

The conditions record this. Subnormal is raised for every tiny result; GDA 1.70 and the functions of this package detect tininess before rounding, from the exact q^\hat q (GDA 1.70, page 11 (Normal numbers, subnormal numbers and Underflow)). Underflow is raised when a tiny result is also inexact (GDA 1.70, pages 11 and 12 (Normal numbers, subnormal numbers and Underflow)), and Clamped when it rounds to zero; the zero then takes the exponent EtinyE_{\mathrm{tiny}} (GDA 1.70, page 12 (Normal numbers, subnormal numbers and Underflow), gives the exponent). Because tininess is decided before rounding, a result such as 0.99510.9951 at p=3p = 3, Emin⁡=0E_{\min} = 0 raises Subnormal and Underflow even though it rounds to the normal number 1.00 (GDA 1.70, page 12 (Normal numbers, subnormal numbers and Underflow), says a subnormal result is indicated even when it rounds to 10Emin⁡10^{E_{\min}}).

GDA 1.70 has no other rule: the after-rounding rule is an IEEE 754 choice for binary formats only (IEEE 754-2019 7.5), so the package has no tininess parameter.

Clamping

With clamp, a result with q>Etopq > E_{\mathrm{top}} but q^≤Emax⁡\hat q \le E_{\max} is representable as a value but not as a triple. Here q^=q+d(c)−1\hat q = q + d(c) - 1 is the adjusted exponent of the result, d(c)d(c) is the number of digits of its coefficient cc, and Etop=Emax⁡−p+1E_{\mathrm{top}} = E_{\max} - p + 1 is the largest exponent a triple of at most pp digits can have. Since q^≤Emax⁡\hat q \le E_{\max} means d(c)+q−1≤Emax⁡d(c) + q - 1 \le E_{\max}, padding the coefficient with q−Etopq - E_{\mathrm{top}} zeros gives

d(c 10q−Etop)=d(c)+q−Etop≤Emax⁡+1−Etop=p,d\bigl(c\,10^{q - E_{\mathrm{top}}}\bigr) = d(c) + q - E_{\mathrm{top}} \le E_{\max} + 1 - E_{\mathrm{top}} = p,

so the padded triple has at most pp digits and the same value. The package does exactly this and raises Clamped; the value is unchanged, only the cohort member differs. Zeros are clamped the same way, by moving their exponent into [Etiny,Etop][E_{\mathrm{tiny}}, E_{\mathrm{top}}].

Overflow

If the rounded result has q^>Emax⁡\hat q > E_{\max} the operation overflows: Overflow, Inexact and Rounded are raised and the result is either ±∞\pm\infty or the largest finite number of the same sign, Nmax⁡=(10p−1)⋅10EtopN_{\max} = (10^p - 1) \cdot 10^{E_{\mathrm{top}}}. Which one follows from treating ∞\infty as the representable number beyond Nmax⁡N_{\max} and applying the rounding algorithm to it as to any other result. The half-way algorithms and Up move away from zero, so they reach ∞\infty. The algorithms Down and ZeroFiveUp move towards zero, so they stop at Nmax⁡N_{\max}: ZeroFiveUp would round away from zero only from a last digit 0 or 5, and the last digit of Nmax⁡N_{\max} is 9. With Ceiling the result is +∞+\infty for a positive and −Nmax⁡-N_{\max} for a negative overflow, and with Floor it is the mirror image (in the source: overflow_to_infinity):

Roundingpositive overflownegative overflow
HalfEven, HalfUp, HalfDown, Up+∞+\infty−∞-\infty
Down, ZeroFiveUp+Nmax⁡+N_{\max}−Nmax⁡-N_{\max}
Ceiling+∞+\infty−Nmax⁡-N_{\max}
Floor+Nmax⁡+N_{\max}−∞-\infty

Conditions, signals and traps

GDA distinguishes conditions (what happened: division by zero, a result was rounded, a conversion was malformed, and so on), signals (the named events a condition triggers) and traps (signals the user has asked to interrupt the computation). The package keeps one flag per condition (thirteen) and one trap-enabler per signal (nine), and maps conditions to the GDA signals by one rule: the four detailed invalid conditions conversion syntax, division impossible, division undefined and invalid context all signal InvalidOperation (GDA 1.70, pages 51 and 52 (Exceptional conditions)). Formally, let S\mathcal S be the thirteen flags and let ι⊂S\iota \subset \mathcal S be the five invalid-family flags. For a set RR of raised flags and a signal σ\sigma,

σ∈∗R  ⟺  {R∩ι≠∅σ=InvalidOperation,σ∈Rotherwise,\sigma \in^\ast R \iff \begin{cases} R \cap \iota \neq \emptyset & \sigma = \mathrm{InvalidOperation},\\ \sigma \in R & \text{otherwise,} \end{cases}

which is GdaFlags::contains. An operation takes operands x⃗\vec x and a context CC and is then the state machine

(x⃗,C)  ⟼  {Completed(v,C,∅)R=∅,Completed(v,C′,R)R≠∅, τ=⊥,Trapped(τ,v,C′,R)τ≠⊥,(\vec x, C) \;\longmapsto\; \begin{cases} \mathrm{Completed}(v, C, \emptyset) & R = \emptyset,\\ \mathrm{Completed}(v, C', R) & R \neq \emptyset,\ \tau = \bot,\\ \mathrm{Trapped}(\tau, v, C', R) & \tau \neq \bot, \end{cases}

where (v,R)=F(x⃗,π(C))(v, R) = F(\vec x, \pi(C)) is the result and the raised flags computed from the operands and the policy π(C)\pi(C) (precision, rounding, exponent range, clamp, extended) alone,

C′.flags=C.flags∪R∪{InvalidOperation∣R∩ι≠∅},C′.π=C.π,C′.traps=C.traps,C'.\mathrm{flags} = C.\mathrm{flags} \cup R \cup \bigl\{\mathrm{InvalidOperation} \mid R \cap \iota \neq \emptyset\bigr\}, \qquad C'.\pi = C.\pi,\quad C'.\mathrm{traps} = C.\mathrm{traps},

and τ\tau is the first signal in the precedence list InvalidOperation, DivisionByZero, Overflow, Underflow, Subnormal, Inexact, Rounded, Clamped, LostDigits with τ∈∗R\tau \in^\ast R and τ∈C.traps\tau \in C.\mathrm{traps}, or ⊥\bot if there is none (in the source: complete_gda and trapped_signal).

Three properties follow directly from the definition and are what users rely on:

  1. The value does not depend on the flags or the traps. vv and RR are functions of (x⃗,π(C))(\vec x, \pi(C)); the flags and the traps only enter C′C' and τ\tau. Enabling a trap therefore never changes a result, and Trapped can carry the defined result.
  2. The flags of the context are monotone and idempotent. C.flags⊆C′.flagsC.\mathrm{flags} \subseteq C'.\mathrm{flags}, and since ∪\cup is associative, commutative and idempotent, the flags after a threaded sequence are the union of all raised sets, independent of how the sequence is grouped.
  3. The trap choice is deterministic. The precedence list is a total order on signals, so one operation selects at most one trap, whatever the order in which its conditions were detected.
///|
test "status is the union of the raised sets" {
  let ctx = @decimal_gda.GdaContext::new(precision=3)
  let d = (s : String) => @decimal_gda.Decimal::from_string(s).unwrap()
  let a = @decimal_gda.divide(d("1"), d("3"), ctx) // Inexact, Rounded
  let b = @decimal_gda.divide(d("1"), d("0"), a.next_context()) // DivisionByZero
  let expected = a.raised().combine(b.raised())
  inspect(b.next_context().flags() == expected, content="true")
  // Trapping changes the variant, never the value.
  let trapping = ctx.trap(Inexact)
  let t = @decimal_gda.divide(d("1"), d("3"), trapping)
  inspect(t.value() == a.value(), content="true")
  inspect(t is @decimal_gda.GdaOutcome::Trapped(Inexact, _, _, _), content="true")
}

Design decisions

Thread status through GdaOutcome, not global state

Problem. The GDA specification describes the context as a mutable object whose flags operations set. GDA 1.70 says that the flags are reset only by explicit user action (page 15 (flags and trap-enablers)). Most implementations (decNumber, Python’s decimal) keep a current context per thread.

Options. (a) A mutable context passed by reference; (b) a thread-local or global current context; (c) an immutable context returned with every result.

Choice: (c). Every GDA function returns GdaOutcome, and the caller passes next_context() to the next operation. The reasons are the three properties of Conditions, signals and traps, and three further facts:

  • FF reads only the policy. The state machine therefore factors into a pure numerical part and a pure bookkeeping part, and both are referentially transparent: an expression can be re-evaluated, memoized or run on another thread without changing its result or its flags.
  • A test runner can snapshot a context and run the same operation under it many times. The .decTest runner in frontend/gda_expr does exactly that.
  • MoonBit has no thread-local storage, so (b) would mean process-global state, which Luna-Flow excludes.

The cost is explicit threading; the decimal_gda_checked package removes it for linear pipelines. When nothing is raised, the input context is returned unchanged, so exact operations do not allocate a new context.

Keep a trap’s defined result

In GDA a trap transfers control, but the specification still defines the result the operation would have delivered, and the trap handler has access to it (GDA 1.70, page 15 (flags and trap-enablers)). Representing a trap as an error (Result::Err, raise) would discard that value. Trapped keeps the value, the next context and the raised set, so the caller can inspect, log or resume from it. Property 1 of Conditions, signals and traps guarantees that it is the same value as without the trap.

Keep the detailed invalid conditions

The specification reports conversion syntax, division impossible, division undefined and invalid context through the signal InvalidOperation (GDA 1.70, pages 51 and 52 (Exceptional conditions)). The package keeps them as separate flags and makes contains(InvalidOperation) true for each. Whenever one of them is raised, invalid_operation is raised in the flags as well.

They are not signals. The trap set has nine trap-enablers, one for each of the signals of the specification, and GDA has no trap-enabler for a condition alone, so a trap cannot be set on one. The decTest files name conditions (Conversion_syntax, Division_undefined, …), which is why the flags stay at thirteen. A program that only knows the GDA signals sees exactly the GDA behaviour, while a test harness or a diagnostic can still tell a malformed literal from 0/00/0. InvalidOperation comes first in the precedence list of Conditions, signals and traps, which makes an InvalidOperation trap catch all four, as the specification requires.

One finalizer, special values first

Each operation first decides the special cases (NaN propagation, invalid operations, infinities, exact zeros), then builds an exact finite coefficient and exponent, and only then calls the shared finalizer of the arithmetic rule. No coefficient algorithm raises a condition. This keeps the conditions a function of the exact result and of the policy of the context (precision, rounding, exponent range, clamp, extended), independent of which multiplication or division kernel was chosen, and lets kernels be tuned without touching the standard-facing behaviour.

A GDA package independent of decimal

IEEE 754-2008 decimal arithmetic grew out of GDA, so the two agree on most finite results, but their contracts differ:

Aspectdecimal_gda (GDA 1.70)decimal (IEEE 754-2019)
Precisionany p≥1p \ge 1 per contextthe format’s pp (or a chosen one)
Roundingeight rounding algorithms (GDA 1.70, pages 13 and 14 (Abstract representation of context)), including HalfUp, HalfDown, ZeroFiveUpthe rounding-direction attributes (IEEE 754-2019 4.3)
Conditionsflags in the context that stay raised until cleared, traps with defined resultsper-operation flags returned with the value
Detailed invalid conditions, LostDigits, subset arithmeticyesno
Tininessbefore roundingbefore rounding
Elementary functionssqrt, exp, ln, log10, powerthe IEEE recommended set
InterchangeDPDDPD and BID

A shared core would have to carry the union of both state models, and a change made for one standard could silently change the other’s results. The package therefore owns its value type, contexts, finalizer and DPD codec, and tools/check_imports.py (part of just pr) fails if it imports decimal, or the reverse.

What the two packages do share is the part that has no standard in it: the integer arithmetic on coefficients, in the internal package internal/decimal_kernel. It contains the limb representation, addition, subtraction, comparison, shifts by powers of ten, digit counts, and the multiplication and division algorithms with their per-target thresholds. Its functions are exact integer functions: they take coefficients and return coefficients, they raise no condition, and they know neither a rounding algorithm, a context nor a flag. A change there cannot change which condition an operation raises, only how fast the exact integer is found, and the kernel imports neither decimal package (tools/check_imports.py checks that too).

A copy of this code in each package is rejected, because the two copies had diverged: a fix in one did not reach the other, and decimal lacked the small-value fast paths of decimal_gda. The thresholds are therefore one set, measured on the shared kernel.

The increment decision of each rounding algorithm is shared too, because it is a pure function of a coefficient and the digits that were discarded: whether the kept magnitude grows by one unit in the last place, for each of the eight rounding algorithms (Rounding to precision gives each). Each package converts its own rounding type (GdaRoundingMode here) into the kernel’s own enumeration of rounding algorithms with one total match, so the kernel knows neither type. What the decision is applied to, and every flag, clamp, subnormal and overflow rule around it, stays in the finalizer of each package. The exact integer helpers on which roots, logarithm series and the logical digit operations are built are shared in the same way.

The engine that accumulates no flags in its context is private to the package (in the source: DecimalContext, DecimalFlags and the *_ctx methods). The functions named after the GDA operations are the only public spelling of every operation, so each operation exists once. The engine returns flags per operation, which is what the Luna-Flow/arithmetic trait implementations use. The IEEE 754 contract lives in decimal.

Fast paths that are proven equivalent

Two kinds of shortcut avoid the general machinery without changing any observable result.

parse, add, subtract, multiply and fma take the small-integer shortcut when all of these hold:

  • all operands are integers with exponent 0 and coefficients below 101810^{18};
  • the exact result is a nonzero integer below 101810^{18} with at most pp digits;
  • its adjusted exponent lies in [Emin⁡,Emax⁡][E_{\min}, E_{\max}];
  • exponent 0 is allowed by clamping;
  • the context is extended.

Under these predicates the general path performs no rounding, raises no condition and returns exponent 0 (the ideal exponent of every one of these operations). The shortcut therefore returns Completed(v, C, none), where vv is the value of the general path and CC the context passed in. A zero result is excluded because its sign depends on the rounding.

An addend that lies below the last retained digit of the other is absorbed. Let x1x_1 and x2x_2 be the operands of an addition, and write qiq_i and q^i\hat q_i for the exponent and the adjusted exponent of xix_i. When x2x_2 is much smaller, q^2<q^1−p+1\hat q_2 < \hat q_1 - p + 1, the exact sum need not be formed. Every digit of x2x_2 lies below the last retained digit of x1x_1, so x2x_2 influences the rounding only through its sign and its comparison with half a unit:

x^=round(x1+x2)=(h+δ(sign⁡x2,  ∣x2∣≶12u))u,\hat x = \mathrm{round}\bigl(x_1 + x_2\bigr) = \bigl(h + \delta(\operatorname{sign} x_2,\; |x_2| \lessgtr \tfrac12 u)\bigr) u,

where hh and uu are the retained head and the unit in the last place of the rounded result, as in Rounding to precision. This is the rounding table of that section with rr replaced by a sticky representative of the same comparison class. The implementation evaluates exactly that (in the source: exact_base_small_addend_result), comparing x2x_2 with u/2u/2 exactly. The case where x1x_1 is a power of ten and x2x_2 has the opposite sign (the unit below x1x_1 is ten times smaller) is excluded and takes the general path.

The shortcut returns the overflow of x1x_1 rounded alone only when the sum overflows as well, because overflow is judged on the rounded sum (see Overflow). That holds in two cases:

  • x2x_2 has the sign of x1x_1, so the sum is larger in magnitude;
  • p≥2p \ge 2 and q^1≥Emax⁡+2\hat q_1 \ge E_{\max} + 2, so the sum is more than 0.9⋅10q^10.9 \cdot 10^{\hat q_1}.

Otherwise an opposite sign can pull the sum back into range, so the case takes the general path: add(9.5, -0.5) at precision 1 and Emax⁡=0E_{\max} = 0 is 9, not an overflow. A non-extended context rounds the operands first, so the shortcut is unchanged there.

The argument needs x1x_1 itself to end at or above the last retained position, so this shortcut is taken only when x1x_1 fits the context exactly (and not under ZeroFiveUp, whose rounding depends on the last kept digit). When x1x_1 has digits below that position, or is exactly a midpoint, x2x_2 can still move the sum across a boundary that the comparison with u/2u/2 does not see. An extended context then replaces x2x_2 by a sticky unit, as the decimal package does. Let tt be the target exponent of x1x_1 alone and g=min⁡(q1,t−2)g = \min(q_1, t - 2). Every digit of x1x_1 and every rounding boundary of the sum lies on the grid 10g10^{g}. The boundaries are the grid 10t10^{t}, its midpoints, and the grid 10t−110^{t-1} with its midpoints, which a cancellation can reach. If 0<∣x2∣<10g0 < |x_2| < 10^{g}, the sum lies strictly between the same two neighbours on that grid as x1±10g−1x_1 \pm 10^{g-1}, with the sign of x2x_2. Rounding that short value once therefore gives the result and the flags of the exact sum under every rounding algorithm. At precision 7, add(1598618.5, 1E-20) under HalfEven is 1598619, and subtract(1598618, 9.9E-11) under ZeroFiveUp is 1598617.

The general route of add and subtract passes through the context-taking engine (operand preparation, the sum, the normalizer, the finalizer, the outcome), whose temporaries are records and tuples that allocate. The plain-sum shortcut avoids them. Let x1x_1 be the operand of larger adjusted exponent. It is taken when:

  • the context is extended and does not clamp;
  • both operands are finite and nonzero;
  • the smaller adjusted exponent is not below q^1−p+1\hat q_1 - p + 1, so no operand is absorbed;
  • the nonzero exact sum has adjusted exponent in [Emin⁡,Emax⁡−1][E_{\min}, E_{\max} - 1], so that after a possible carry into a digit beyond pp it can neither overflow nor be subnormal, and its exponent is not clamped.

The result is then the exact aligned sum rounded once to pp digits at the exponent min⁡(q1,q2)\min(q_1, q_2) plus the digits discarded, with rounded raised when digits were discarded and inexact when a nonzero one was. Dropping a run of zero digits first and then rounding the rest gives the same value, exponent and flags as rounding once. The shortcut computes that result directly (in the source: gda_add_plain):

  • The sum is formed in one limb array and rounded in place by the kernel (see the design of internal/decimal_kernel).
  • The flags are shared constants. Sharing is not observable, because GdaFlags and DecimalFlags are immutable records compared by value.
  • The outcome is built once. When the flags of the context already contain the raised conditions, the outcome carries the input context itself.

Every other case returns None and takes the general route, which remains the definition. A test compares both routes for add and subtract (conformance).

multiply and divide take the same kind of shortcut as the plain sums, under the same predicates: an extended context without clamping, finite nonzero operands, and a result whose adjusted exponent lies in [Emin⁡,Emax⁡−1][E_{\min}, E_{\max} - 1], so that it can neither overflow, nor be subnormal, nor change exponent for the exponent range. A product is the exact product rounded once to pp digits at the exponent q1+q2q_1 + q_2 plus the digits discarded.

A quotient is formed in four steps. Let aa and bb be the coefficients of dividend and divisor, with nan_a and nbn_b digits, and k=max⁡(0,p+2+nb−na)k = \max(0, p + 2 + n_b - n_a) (a meaning of kk local to this section).

  1. Divide a⋅10ka \cdot 10^{k} by bb once. The quotient has at least p+2p + 2 digits.
  2. Round it with ZeroFiveUp, so that a nonzero remainder leaves the last digit off 0 and 5 (see Rounding to precision).
  3. Round the result once to pp digits.
  4. Raise rounded and inexact.

A quotient with a finite decimal expansion (the remainder test of the same division) is left to the general route, because its exponent follows the ideal exponent rules. The general route scales the dividend by 10p+nb+210^{p + n_b + 2} whatever nan_a is, which makes the quotient about twice as long as it must be. The value, the exponent and the flags of an inexact quotient do not depend on the number of guard digits beyond p+2p + 2, because rounding sees the discarded part only through its position relative to the midpoints, and ZeroFiveUp preserves that. The plain path therefore uses the shorter scale. A test compares both routes for multiply and divide (conformance).

Division

divide handles 00, ∞\infty and exact divisions by powers of ten and by small exact divisors separately. Every other quotient takes three steps. Let c1c_1 and c2c_2 be the coefficients of the dividend and the divisor, and pp the precision of the context.

  1. Scale the dividend by 10T10^{T} with T=p+d(c2)+2T = p + d(c_2) + 2. The scaled quotient is Q=c110T/c2Q = c_1 10^{T} / c_2. Since c1≥1c_1 \ge 1 and c2<10d(c2)c_2 < 10^{d(c_2)}, the quotient satisfies Q≥10p+2Q \ge 10^{p+2}, so QQ has at least p+3p + 3 integer digits.
  2. Round QQ to an integer Q0Q_0 with ZeroFiveUp, the rounding algorithm of Rounding to precision; the tie it prevents is shown in the example of the half-way algorithms.
  3. Round Q0Q_0 to pp digits with the rounding of the context.

Whether the quotient terminates is decided exactly: c1/c2c_1/c_2 terminates iff c2/gcd⁡(c1,c2)c_2 / \gcd(c_1, c_2) has no prime factors other than 2 and 5 (in the source: has_finite_decimal_expansion_repr). The decision selects the ideal-exponent cohort for exact quotients and forces Inexact with a pp-digit coefficient for the others. An exact quotient that needs rounding, from any of these paths, goes to the subnormal grid only when its value is below 10Emin⁡10^{E_{\min}}. Otherwise it is rounded once to pp digits, as in the finalizer. At precision 5, divide(77223, 16E+21) is 4.8264E-18.

For the directed algorithms the two successive roundings are equivalent to one, because truncations compose: for a real yy and integers j,m≥0j, m \ge 0, ⌊⌊y/10j⌋/10m⌋=⌊y/10j+m⌋\lfloor \lfloor y/10^j \rfloor / 10^m \rfloor = \lfloor y/10^{j+m} \rfloor. That is, truncating twice is truncating once at the coarser position.

For the half-way algorithms a first rounding by the rounding of the context could manufacture a tie: the discarded digits of Q0Q_0 are exactly 50⋯050\cdots0 while Q≠Q0Q \ne Q_0. At precision 1, 1/2222=0.00045004…1/2222 = 0.00045004\ldots would give Q0=4500Q_0 = 4500 (unit 10−710^{-7}), and the second rounding would see a tie and return 0.0004. The first rounding therefore uses ZeroFiveUp. When Q≠Q0Q \ne Q_0 it leaves a last digit other than 0 and 5. A pp-digit number and a pp-digit midpoint both end in 0 or 5 in the unit of Q0Q_0, so Q0Q_0 is neither of them and lies strictly on the same side of every such point as QQ. The second rounding then returns ∘p(Q)\circ_p(Q) for every rounding algorithm ∘\circ, where ∘p(x)\circ_p(x) is xx rounded to pp digits by ∘\circ. So divide(1, 2222) at precision 1 is 0.0005.33 This is decNumber’s DEC_ROUND_05UP device; GDA 1.70, page 14 (Abstract representation of context) gives round-05up for the same purpose, arithmetic at shorter lengths without double rounding. With the rounding of the context in the first rounding, a sweep of c1<20c_1 < 20, c2<3000c_2 < 3000, p≤3p \le 3 finds 12 misrounded quotients.

Square root

The function sqrt first tries an exact root. Let cc be the coefficient and qq the exponent of the operand. The function removes trailing zeros, makes the exponent even and takes the integer square root (z,ρ)(z, \rho) of cc, with z2+ρ=cz^2 + \rho = c, by Newton’s iteration, which updates the iterate aa by a←⌊(a+⌊c/a⌋)/2⌋a \leftarrow \lfloor (a + \lfloor c/a \rfloor)/2 \rfloor. It accepts ρ=0\rho = 0 and then pads towards the ideal exponent ⌊q/2⌋\lfloor q/2 \rfloor within pp digits (GDA 1.70, page 39 (square-root)). An exact root longer than pp digits is an exact result like any other, so the finalizer rounds it once, ties included: at p=1p = 1, 2.25=1.5\sqrt{2.25} = 1.5 is a tie, which gives 2 under HalfEven and 1 under HalfDown.

Otherwise the root is irrational and the package rounds it directly at the final position. The root exponent is f=max⁡(Etiny,⌊q^/2⌋−p+1)f = \max(E_{\mathrm{tiny}}, \lfloor \hat q/2 \rfloor - p + 1), the scaled radicand is M=c 10q−2fM = c\,10^{q - 2f}, and the integer root is z=⌊M⌋z = \lfloor \sqrt{M} \rfloor. The increment is decided by comparing the radicand with the square of the midpoint, which is exact in integers:

M≷z+12  ⟺  4M≷(2z+1)2.\sqrt{M} \gtrless z + \tfrac12 \iff 4M \gtrless (2z + 1)^2 .

Rounding once at ff (not first at pp digits and then again at EtinyE_{\mathrm{tiny}}) avoids double rounding of tiny roots. Because exact roots were handled first, the comparison only ever decides an irrational root, which cannot equal a midpoint, so the strict comparison decides every rounding algorithm. When q−2f<0q - 2f < 0 the radicand MM is not an integer; the comparison is then made as 4c≷(2z+1)2 102f−q4c \gtrless (2z+1)^2\,10^{2f - q}, still in integers, so no digit of cc is truncated. The GDA function sqrt always rounds half to even (GDA 1.70, page 39 (square-root)).

The route above can be shortened for an operand that is certainly not a square. It takes one root to find out whether the operand is a square and, for a non-square, a second root at the final position, with a midpoint comparison that forms three products as long as the radicand. A random operand is never a square, and the second root already decides the rounding. What remains is to recognise a non-square without taking a root of it. The plain path (in the source: decimal_sqrt_plain) rests on two steps.

  1. One root decides the rounding. With MM and zz of the irrational root and ρ=M−z2\rho = M - z^2, the root is exact iff ρ=0\rho = 0. Otherwise M>(z+12)2M > (z + \tfrac12)^2 iff ρ>z\rho > z, because (z+12)2=z2+z+14(z + \tfrac12)^2 = z^2 + z + \tfrac14 and ρ\rho is an integer. The comparison with the midpoint is therefore one comparison of ρ\rho with zz.
  2. A non-square is recognised without taking a root of it. Write the operand as c010kc_0 10^{k} with c0c_0 not divisible by 10, so that c0c_0 is the coefficient without its trailing zeros and kk is qq plus their number. The root is a decimal iff kk is even and c0c_0 is a square. If kk were odd, 10c010 c_0 would have to be a square, so the root would be divisible by 10, and 1010 would divide c0c_0. If kk is even, the root is c0 10k/2\sqrt{c_0}\,10^{k/2}, a decimal only when c0\sqrt{c_0} is one, that is, when c0c_0 is a square, since the square root of an integer is an integer or irrational. A square is a square modulo every integer, so the plain path takes an operand whose kk is odd, or whose c0c_0 is not a square modulo 64, 63, 65 or 11 (a remainder by a word each, from the lowest limbs). The operands that pass all four tests, every square and about one non-square in 120, are left to the route above. A square therefore pays the five remainders and does not pay a root twice as long as it needs.

The path also requires:

  • the root is neither subnormal nor possibly beyond the range, Emin⁡≤⌊q^/2⌋<Emax⁡E_{\min} \le \lfloor \hat q/2 \rfloor < E_{\max}, so the exponent of the result, after a carry too, is at most Emax⁡−p+1E_{\max} - p + 1 and no clamp folds it;
  • the radicand is an integer, q−2f≥0q - 2f \ge 0, that is, a coefficient of at most 2p2p digits.

The result has exactly pp digits at the exponent ff; Inexact and Rounded are raised. A white-box test compares it with the route above at the public level (value, every condition, the flags of the context), on random operands, squares and near squares (conformance).

Integer powers

For a base xx and an integer exponent nn, the result follows GDA 1.70, page 35 (power). If the exact power fits in pp digits, it is returned exactly with exponent nqn q, where qq is the exponent of xx. Otherwise binary powering runs at working precision w=p+d(∣n∣)+2w = p + d(|n|) + 2 digits, one digit fewer in subset contexts, where d(∣n∣)d(|n|) is the number of digits of ∣n∣|n|. Every product is rounded with HalfEven, and the final product is rounded to the context.

A negative nn starts from a rounded 1/x1/x in extended contexts; in subset contexts the reciprocal is taken at the end. If that reciprocal already overflows the working context, the power overflows. The sign of the overflowed result is the sign of xnx^n (negative only for a negative xx and an odd nn), not the sign of xx: (−0.07)−8(-0.07)^{-8} overflows to +∞+\infty and (−0.07)−7(-0.07)^{-7} to −∞-\infty.

The reciprocal keeps the cohort of the division (1/5×10−21 / 5 \times 10^{-2} is 2×1012 \times 10^{1}, not 2020). The reason is that the exponent of an exact power is the one repeated multiplication gives: 0.05−80.05^{-8} is 2.56×10102.56 \times 10^{10} with three digits and no Rounded.

A zero exponent is decided before all of this. For a finite nonzero xx (and for ±∞\pm\infty), x0x^0 is the integer 11 with exponent 00 and raises no condition in every context, a clamped one included (GDA 1.70, page 35 (power): “the result will be 1 and exact”). The result is not folded down, as decNumber does not fold it (decNumberPower leaves by an early exit before its final rounding and clamping, decCopyFit and decFinish) and as libmpdec does not.

The IEEE interchange encoders fold a result down themselves, at an exponent above Emax⁡−Pmax⁡+1E_{\max} - P_{\max} + 1, where Emax⁡E_{\max} and Pmax⁡P_{\max} are the maximum exponent and the precision of the format. That is 90, 369 and 6111 for decimal32, decimal64 and decimal128, which the exponent 00 of 11 never reaches. Only a clamped context with Emax⁡<p−1E_{\max} < p - 1, which no IEEE format has, could tell the two results apart.

The working context never clamps, so Clamped and Rounded come from two places only. An intermediate rounding that discards non-zero digits makes the result inexact. The final rounding to the context folds down an exponent above EtopE_{\mathrm{top}} and raises Clamped when it does. An exact result such as (−0.5)−2=4(-0.5)^{-2} = 4 at precision 1 and Emax⁡=0E_{\max} = 0 raises neither.

Error of binary powering. Write uw=12101−w\mathbf u_w = \frac12 10^{1-w}, the unit roundoff of precision ww for the half-way algorithms (Rounding to precision), and let δ\delta, with ∣δ∣≤uw|\delta| \le \mathbf u_w, be the relative error of one rounding. Let the accumulator hold xℓ(1+θℓ)x^\ell(1 + \theta_\ell), where ℓ\ell is the power of xx it has reached and θℓ\theta_\ell its relative error. A squaring gives x2ℓ(1+θℓ)2(1+δ)x^{2\ell}(1+\theta_\ell)^2(1+\delta) and a multiplication by xx gives xℓ+1(1+θℓ)(1+δ)x^{\ell+1}(1+\theta_\ell)(1+\delta), so 1+∣θ2ℓ∣≤(1+∣θℓ∣)2(1+uw)1 + |\theta_{2\ell}| \le (1+|\theta_\ell|)^2(1+\mathbf u_w) and 1+∣θℓ+1∣≤(1+∣θℓ∣)(1+uw)1 + |\theta_{\ell+1}| \le (1+|\theta_\ell|)(1+\mathbf u_w). By induction on the binary expansion, 1+∣θℓ∣≤(1+uw)ℓ−11 + |\theta_\ell| \le (1+\mathbf u_w)^{\ell-1} for every ℓ≥1\ell \ge 1: the error of binary powering is that of ℓ−1\ell - 1 successive roundings, although only about 2log⁡2ℓ2\log_2 \ell products are formed.22 N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM 2002, section 2.2. Decimal wobble is larger than binary: the relative spacing varies by a factor of 10 across a decade, against 2 in binary (Goldberg 1991, section 1.2). Starting from a rounded reciprocal adds the factor (1+uw)∣n∣(1+\mathbf u_w)^{|n|}, because its error is raised to the power ∣n∣|n|. Let mm be the exponent of the factor 1+uw1 + \mathbf u_w in the whole bound: m=∣n∣−1m = |n| - 1 for n>0n > 0 and m=2∣n∣−1m = 2|n| - 1 for n<0n < 0. With muw≤10−pm \mathbf u_w \le 10^{-p},

∣θ∣≤(1+uw)m−1≤m uw (1+m uw),∣n∣ uw<10d(∣n∣)⋅12 101−p−d(∣n∣)−2=12 10−1−p.|\theta| \le (1 + \mathbf u_w)^{m} - 1 \le m\,\mathbf u_w\,(1 + m\,\mathbf u_w), \qquad |n|\,\mathbf u_w < 10^{d(|n|)} \cdot \tfrac12\,10^{1 - p - d(|n|) - 2} = \tfrac12\,10^{-1-p}.

Error in units in the last place. The exact result yy satisfies ∣y∣<10p u|y| < 10^{p}\,u for the unit uu in the last place of the rounded result, so a relative error θ\theta is at most ∣θ∣ 10p|\theta|\,10^p units. This gives the working error of the second column of the table below, in units in the last place. Adding the final rounding gives the bound for an inexact integer power in the other two columns.

ExponentWorking error, at most (units)Final result, half-way algorithms, within (units)Final result, directed algorithms, within (units)
n>0n > 00.050.050.550.551.051.05
n<0n < 00.10.10.60.61.11.1

In subset contexts ww is one digit smaller, so the working error grows tenfold and the bound for the half-way algorithms becomes about 11 unit. None of this is correct rounding: a power whose exact result lies within 0.10.1 units of a rounding boundary can round the wrong way. The specification does not require more for integer powers (GDA 1.70, page 35 (power)).

Exponents that overflow or underflow. Exponents so large that the result must overflow or underflow are detected beforehand from the bounds n(q^+1)−1n(\hat q + 1) - 1 and nq^n \hat q on the adjusted exponent of the result, where q^\hat q is the adjusted exponent of xx. The underflow shortcut is taken only when the upper bound is at most Etiny−2E_{\mathrm{tiny}} - 2, so the exact power is below 1210Etiny\tfrac12 10^{E_{\mathrm{tiny}}}. The result is then that value rounded by the rounding algorithm of the context: zero for the half-way algorithms and Down, and ±10Etiny\pm 10^{E_{\mathrm{tiny}}} when the rounding algorithm rounds away from zero for the result’s sign.

Digits of an inexact result. An inexact result is delivered with a coefficient of pp digits. The working arithmetic drops the trailing zeros of the rounded value, so they are restored after the final rounding. GDA 1.70, page 23 (Arithmetic operations), says a result with more digits than the precision is “rounded (shortened) to exactly precision digits”, and IEEE 754-2019 5.2 selects the cohort member of least possible exponent for an inexact result. A non-integer exponent gives the same (non-integer power). power(99999E-1, -1) at precision 2 is 0.00010. Only a subset context strips the zeros, as GDA 1.70, page 56 (Appendix A, The X3.274 subset), prescribes, and a subnormal result has fewer digits because its exponent is EtinyE_{\mathrm{tiny}}.

Tininess. Tininess is judged on the exact power, before rounding: GDA 1.70, page 53 (Exceptional conditions), raises Subnormal when the adjusted exponent is below Emin⁡E_{\min} “before any rounding”, and Underflow when the result is also inexact. The working arithmetic only sees the power rounded to ww digits, so when the delivered result is exactly 10Emin⁡10^{E_{\min}} the side of the exact power is decided separately:

  1. The power is recomputed at precision w′=p+d(∣n∣)+6w' = p + d(|n|) + 6. Its relative error is below 10d(∣n∣)+2−w′10^{d(|n|) + 2 - w'}, since it is at most 2∣n∣2|n| roundings of uw′\mathbf u_{w'}.
  2. The recomputed power is compared with 10Emin⁡(1±10d(∣n∣)+2−w′)10^{E_{\min}}(1 \pm 10^{d(|n|) + 2 - w'}).
  3. A power outside that band is subnormal exactly when it is below 10Emin⁡10^{E_{\min}}. While the power is inside the band, w′w' is doubled and the power recomputed, five attempts in all.

For 1/1.000000000000000000011/1.00000000000000000001 at p=1p = 1 and Emin⁡=0E_{\min} = 0 the exact result 0.999999999999999999990.99999999999999999999 is separated at w′=32w' = 32, so the result 1 raises Subnormal and Underflow. The test is made only when tininess is detected before rounding, as GDA does (GDA 1.70, page 53 (Exceptional conditions)).

Correctly rounded exp, ln, log10 and non-integer power

These functions return the correctly rounded result, which they decide by certified interval arithmetic and a Ziv-style refinement loop.44 A. Ziv, “Fast evaluation of elementary mathematical functions with correctly rounded last bit”, ACM TOMS 17(3), 1991. On ball arithmetic see J. van der Hoeven, “Ball arithmetic”, 2009, and F. Johansson, “Arb: efficient arbitrary-precision midpoint-radius interval arithmetic”, IEEE Trans. Computers 66(8), 2017. A result is certified when an interval known to contain f(x)f(x) lies inside its rounding cell. For f(x)f(x), with xx the operand (the base, for power, whose exponent is yy), the evaluation has five steps.

  1. The exact cases are decided first and never reach the loop. They are exp⁡0=1\exp 0 = 1, ln⁡1=0\ln 1 = 0, log⁡1010k=k\log_{10} 10^k = k, special operands, domain errors, and the cases power can decide exactly:

    • x1/2x^{1/2}, by sqrt;
    • powers of ten and 1y1^y;
    • guaranteed overflow or underflow;
    • exact rational powers: y=a/by = a/b in lowest terms with xx a perfect bb-th power, such as 41.5=84^{1.5} = 8. The root is taken before the power, so no intermediate is longer than the result;
    • 10k10^k to a non-integral yy with kyky an integer, which is the exact 10ky10^{ky} in every rounding algorithm (in the source: decimal_power_ten_noninteger_result).

    The loop could never certify an exact result: it is a boundary of its rounding cell in the directed algorithms, and an exact midpoint is one in the half-way algorithms.

  2. The input is enclosed: xx is converted to a binary interval [x−,x+][x^-, x^+] at wbitsw_{\mathrm{bits}} bits, the working precision of the evaluation, with directed rounding (to_binary towards −∞-\infty and +∞+\infty), so that x∈[x−,x+]x \in [x^-, x^+] exactly.

  3. The output is enclosed: interval evaluates ff on this interval and returns an enclosure [y−,y+]∋f(x)[y^-, y^+] \ni f(x). For log10 it divides ln⁡\ln by a cached enclosure of ln⁡10\ln 10; for power it evaluates exp⁡(yln⁡x)\exp(y \ln x) through enclosures of ln⁡x\ln x.

  4. A candidate is certified. A decimal approximation y~\tilde y of f(x)f(x) (the midpoint of the enclosure; power may use a decimal series evaluation) is rounded to the context, which gives rr. The candidate is only a guess that the test below certifies. The result is rr when the whole enclosure lies strictly inside the rounding cell of rr, and then the midpoint of the enclosure, which belongs to the cell, rounds to the same cell.

    exp therefore takes the midpoint as its candidate. When ∣x∣≥103|x| \ge 10^3 the midpoint is a binary floating-point number of enormous exponent, and exp takes the series with the same number of digits instead. The candidate is converted to max⁡(p+8,⌊0.31 wbits⌋+4)\max(p + 8, \lfloor 0.31\,w_{\mathrm{bits}} \rfloor + 4) digits, so that the conversion error is below the radius of the enclosure and cannot carry the candidate onto a cell boundary that the enclosure itself avoids.

    Let (α,β)(\alpha, \beta) be the open interval of reals around rr that round to rr. For the half-way algorithms its bounds are the two midpoints between rr and its neighbours r−r^- and r+r^+ below and above it. For the directed algorithms it is (r,r+)(r, r^+) or (r−,r)(r^-, r). The real rounding cell of a directed algorithm is half-open, [r,r+)[r, r^+) or (r−,r](r^-, r]; the test uses the open interior, which is sufficient. The bounds α\alpha and β\beta are exact decimals. Each is enclosed in binary, with α+\alpha^+ the upper bound of the enclosure of α\alpha and β−\beta^- the lower bound of the enclosure of β\beta, and the result is accepted when

    α≤α+<y−≤f(x)≤y+<β−≤β,\alpha \le \alpha^+ < y^- \le f(x) \le y^+ < \beta^- \le \beta ,

    which proves round(f(x))=r\mathrm{round}(f(x)) = r, where round\mathrm{round} is the rounding to the context. A second test rounds both bounds y−y^- and y+y^+ of the enclosure, which are exact dyadic numbers, to the context. Since every rounding algorithm is monotone, round(y−)=round(y+)=r\mathrm{round}(y^-) = \mathrm{round}(y^+) = r also proves round(f(x))=r\mathrm{round}(f(x)) = r.

  5. Otherwise the evaluation is refined. The working precision grows, wbits←wbits+max⁡(32,⌊wbits/2⌋)w_{\mathrm{bits}} \leftarrow w_{\mathrm{bits}} + \max(32, \lfloor w_{\mathrm{bits}}/2 \rfloor), and the loop repeats. At most LL evaluations are made, where LL is the refinement limit of the GdaContext (GdaContext::refinement_limit, default twelve). From the start value wbits,0≥128w_{\mathrm{bits},0} \ge 128 below the increment is ⌊wbits/2⌋≥64\lfloor w_{\mathrm{bits}}/2 \rfloor \ge 64, so each step multiplies the precision by about 1.5 and the last of twelve evaluations runs at roughly 1.511≈861.5^{11} \approx 86 times the starting precision.

The starting precision is wbits,0=max⁡(128,4D+64)w_{\mathrm{bits},0} = \max(128, 4D + 64) bits, where D=max⁡(d(c),p)D = \max(d(c), p), d(c)d(c) is the number of digits of the coefficient cc of xx and pp is the precision of the context. Four bits per decimal digit exceed log⁡210≈3.32\log_2 10 \approx 3.32, so the input is carried without loss of decimal information and 64 guard bits remain. For arguments with q^=0\hat q = 0 in a wide, unclamped context with p≤64p \le 64, a cheaper first attempt uses about 103D+12\frac{10}{3} D + 12 bits and falls back to wbits,0w_{\mathrm{bits},0} if it cannot certify.

The loop always stops, after at most LL evaluations (twelve by default). With with_refinement_limit(None) the count is unbounded, but the loop still stops when the working precision passes max⁡(8 000 000, 256 wbits,0)\max(8\,000\,000,\ 256\,w_{\mathrm{bits},0}) bits (at most 10910^9), with the same certification failure, so the work and the memory stay bounded.

The loop certifies a result whenever f(x)f(x) is neither a representable number nor, for the half-way algorithms, a midpoint, and the refinement limit and the resource bound are large enough. The reason is that the enclosure shrinks to a point while f(x)f(x) stays at a positive distance from every rounding boundary. For exp, ln and log10 the condition on f(x)f(x) holds for every operand that step 1 leaves. Representable numbers and midpoints are rational, so it is enough that f(x)f(x) is irrational:

  • For exp, xx is rational and not 0. By the Lindemann–Weierstrass theorem ex\mathrm{e}^x is transcendental, hence irrational.
  • For ln, xx is rational and not 1. If ln⁡x\ln x were rational, it would be nonzero, and x=eln⁡xx = \mathrm{e}^{\ln x} would be transcendental by the same theorem, which a rational xx is not. So ln⁡x\ln x is irrational.
  • For log10, log⁡10x=ln⁡x/ln⁡10\log_{10} x = \ln x / \ln 10 is rational only for integral powers of ten, which step 1 decides.

If the refinement limit or the resource bound is exhausted, for example for a power whose exact result is a midpoint and is not caught in step 1, the try_exp, try_ln, try_log10 and try_power functions return a certification failure and the GDA functions return NaN with InvalidOperation. An unproven result is never returned.

The GDA functions exp, ln, log10 and sqrt pass a copy of the context with HalfEven rounding, because the specification defines these functions as correctly rounded with round-half-even regardless of the rounding of the context (GDA 1.70, page 30 (exp); page 31 (ln and log10); page 39 (square-root)). power uses the rounding of the context, as the specification and its test vectors require.

power reports a non-integer power as Inexact with pp digits even when the power happens to be exact (in the source: decimal_power_noninteger_gda_result; GDA 1.70, page 35 (power), calls every such result inexact). It never reports Clamped unless the result rounds to zero. The padded form of a nonzero result has an exponent of at most Emax⁡−p+1E_{\max} - p + 1, so no fold-down is left to report, whatever route computed it (a square root for the exponent 0.50.5, an exact rational power, a power of ten, the certified loop). The exact result is the correctly rounded one under every rounding algorithm, so a directed algorithm never adds a unit in the last place: power(1E-5, 1.2) is 1E-6 padded to pp digits with Inexact and Rounded in every rounding algorithm, as power.decTest rows powx2039 and powx2040 show for 1y1^y in ceiling.

exp, ln, log10 and power with a non-integer exponent accept only contexts with pp, Emax⁡E_{\max} and −Emin⁡-E_{\min} at most 999,999 (math_context_is_restricted) and raise InvalidContext otherwise. This is an implementation limit, decNumber’s DEC_MAX_MATH, and not a rule of the GDA operation text. The official decTest suite requires it (power.decTest powx4001 to powx4005 and the matching rows of exp.decTest, ln.decTest and log10.decTest), and GDA 1.70 permits it through the Invalid context condition, which covers a precision that exceeds the capability of the implementation (GDA 1.70, page 52 (Exceptional conditions)). The API page states the limit and the operands it applies to.

In subset arithmetic ln reproduces the result of the classic reference algorithm, which can be one unit in the last place above the correctly rounded one (in the source: decimal_ln_subset_result), because the legacy subset test vectors encode that result.

Coefficient representation and kernels

The kernel lives in internal/decimal_kernel and is shared with decimal (why). A coefficient is either Small(UInt64) for values below 101810^{18} or an array of base-10910^9 limbs with a cached digit count. Both are persistent: operations never mutate operand limbs. Decimal limbs make digit counts, trailing-zero removal, the half-unit comparison and the ZeroFiveUp last-digit test constant-time or linear, without a binary-to-decimal conversion. Multiplication and division choose among schoolbook, Karatsuba, Toom-3, a dual-modulus NTT, Knuth’s algorithm D, Burnikel–Ziegler and Newton reciprocal division by limb count, with thresholds per target:

TargetKaratsuba mul / squareToom-3first NTT mul / squareBurnikel–ZieglerNewton division
native96 / 481,1521,728 / 640from 2,816off
LLVM96 / 962,0484,096 / 2,0482,0484,096
Wasm, Wasm-GC, JS96 / 964,0968,192 / 4,0962,0484,096

The thresholds are measured performance policy, not semantics: every kernel returns the exact product or quotient, so the choice cannot change a result or a flag. See performance for the measurements.

Correctness and invariants

  • Correct rounding. Every finite result other than integer power, the division case and the to-integral operations on integers longer than pp digits is correctly rounded: it is the exact result xx rounded once, to the returned result x^\hat x. Let uu be the unit in the last place of x^\hat x. Then ∣x^−x∣≤12u|\hat x - x| \le \frac12 u in the half-way algorithms and <u< u in the directed algorithms and ZeroFiveUp, and ∣x^−x∣/∣x∣≤12101−p|\hat x - x|/|x| \le \frac12 10^{1-p} outside the subnormal range.
  • Ideal cohort. An exact result is returned at the representable exponent nearest to its ideal exponent, so operations on exact data keep their exponent (2.50 × 3 = 7.50).
  • Independence of the flags. The result F(x⃗,C)F(\vec x, C) of an operation on x⃗\vec x in the context CC depends on CC only through its policy π(C)\pi(C) (see Conditions, signals and traps): results never depend on the flags of the context or on the traps.
  • Flags algebra. The flags of a context only grow, and after a threaded sequence of operations they are the union of the sets of conditions the operations raise.
  • Trap determinism. At most one trap fires per operation, selected by a fixed total order; Trapped carries the same value as Completed would.
  • Proof before return. A finite inexact result of exp, ln, log10 or non-integer power is returned only together with a proof (Lemma 3 or 4 of the rounding proofs) that it is the correctly rounded result; a failure to prove it yields NaN and InvalidOperation.
  • Total order. compare_total is a total order on triples (sign, then class, then value, then exponent, then payload), and Decimal::compare is a total preorder in which NaNs form one class above all other values.
  • Checked results. The pinned official test suite and the legacy official0 suite pass all their legal executable rows (conformance). These are finite sets of rows: no pinned row covers the tie in division in the half-way algorithms (Division) or a to-integral operand longer than the precision.

Alternatives rejected

  • A mutable or global current context. Rejected because it makes results and flags depend on evaluation order and hidden state (see the first design decision).
  • Traps as errors. Rejected because the GDA-defined result would be lost.
  • Sharing the engine with decimal. Rejected because one standard’s change could alter the other’s results. A measured duplication is cheaper than an accidental semantic coupling.
  • Binary floating point for elementary functions with a fixed number of guard digits. Rejected because no fixed number of guard digits guarantees correct rounding (the table-maker’s dilemma); a proof with refinement does, and fails visibly when it cannot be completed.
  • Reducing every result. Rejected because the exponent, and with it the quantum 10q10^q, is part of a finite number in GDA. reduce removes the trailing zeros when the caller asks for it.

Boundaries

  • The package implements the GDA operations and nothing else: no trigonometric, hyperbolic or other functions outside the specification, and no IEEE 754 operations.
  • It does not parse .decTest files, run test suites or read files; that is frontend/gda_expr and the repository tools.
  • It provides DPD interchange and no BID interchange.
  • It gives no correct rounding for integer powers beyond the GDA requirement.
  • It provides no mutable or global context, and contexts carry no identity: two contexts with the same fields are interchangeable.
  • ParseChecked is a value-only adapter over the GDA to-number conversion. It maps ArithmeticContext to the engine context, so the precision, the rounding, the exponent limits and the clamp apply. The returned Result cannot carry the flags or traps of GDA; a caller that needs them uses to_number with a GdaContext.
  • It stores no exponent beyond the implementation limit on the exponents of a stored value: a finite number needs an exponent of at least −231+3-2^{31}+3 and an adjusted exponent of at most 231−22^{31}-2, the range of the working context of the plain operators. The constructors reject a value outside it (they never replace it silently), context operations overflow or underflow against the context range, decided from the exact exponent, and the operations without a context overflow or underflow at the implementation limit.

Footnotes

  1. M. F. Cowlishaw, General Decimal Arithmetic Specification, version 1.70 (2009), https://speleotrove.com/decimal/decarith.html. The test suite is the same author’s dectest collection, version 2.62. ↩

  2. N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM 2002, section 2.2. Decimal wobble is larger than binary: the relative spacing varies by a factor of 10 across a decade, against 2 in binary (Goldberg 1991, section 1.2). ↩ ↩2

  3. This is decNumber’s DEC_ROUND_05UP device; GDA 1.70, page 14 (Abstract representation of context) gives round-05up for the same purpose, arithmetic at shorter lengths without double rounding. With the rounding of the context in the first rounding, a sweep of c1<20c_1 < 20, c2<3000c_2 < 3000, p≤3p \le 3 finds 12 misrounded quotients. ↩

  4. A. Ziv, “Fast evaluation of elementary mathematical functions with correctly rounded last bit”, ACM TOMS 17(3), 1991. On ball arithmetic see J. van der Hoeven, “Ball arithmetic”, 2009, and F. Johansson, “Arb: efficient arbitrary-precision midpoint-radius interval arithmetic”, IEEE Trans. Computers 66(8), 2017. ↩