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 with sign , coefficient and exponent , denoting
The map is not injective: and both denote . 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 , and “2.50” was measured to the cent. Zero is signed, so is . For write for the number of decimal digits of and
for the adjusted exponent, the exponent of the leading digit: . Besides finite numbers there are the special values and the quiet and signaling NaNs, which carry a sign and a payload .
Contexts and the representable set
A context fixes a precision , a rounding, an exponent range and a clamp bit. A finite number is representable in the context when
and, if clamping is on, also .
The value is the exponent of the smallest unit. A number
with and digits has , and numbers
below (the subnormal range) keep that unit while losing
leading digits. The value is the exponent of the largest
-digit number with . 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:
- compute the exact mathematical result and choose, among the triples that denote , the one whose exponent is closest to the operation’s ideal exponent ;
- 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 and , and the operand of the square root as , leaving signs aside. Let be the smaller of the two exponents, . The derivations are short:
For addition, 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 is an integer at exponent and in general at no larger one. For division the quotient need not be an integer, so the ideal is used only when it is reachable. The exact quotient is written with the exponent nearest to that keeps an integer coefficient of at most digits, and an inexact quotient uses all digits. For the square root, is the exponent of the root whose square has the largest even exponent not above , namely .
The table lists the ideal exponent of each operation. In it, is
the integer operand of scaleb and of an integer power, and is an integer.
| Operation | Ideal exponent |
|---|---|
add, subtract, fma (sum part) | |
multiply, fma (product part) | |
divide | if exact, else digits |
sqrt | if exact, else digits |
remainder, remainder_near | |
divide_integer, to_integral_* | for the integral value, 0 for a quotient |
quantize, rescale | the requested exponent |
scaleb | |
power with integer , exact | |
exp, ln, log10, non-integer power | digits (always inexact, except exp(0), ln(1), log10(10^k)) |
plus, minus, abs, apply |
A zero result has no leading digit, so its exponent is simply the ideal one,
clamped into , or into
under clamping. For a zero, quantize and rescale
follow the rule too: the requested exponent must be at most
, and under clamp one above 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 except when rounding towards .
///|
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 digits of the
context’s precision. Let the exact result be , with sign
, coefficient and exponent , and let with ,
where is the number of decimal digits of . Divide off the low
digits, with , so that is the retained
head and the discarded tail. Each of the eight rounding algorithms (GDA
1.70, pages 13 and 14 (Abstract representation of context)) returns
with an increment ,
and the eight differ only in (in the source:
should_increment_decimal_repr). Below, is 1 when the condition
holds and 0 otherwise:
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 versus is done exactly on the decimal
limbs of the coefficient (in the
source: dec_coeff_div_pow10_round_info_repr returns the quotient, whether
, and the sign of ). If , the rounded
coefficient has digits; its last digit, a zero, is dropped and the
result is (GDA 1.70, page 14 (Abstract representation of context)). Before rounding,
the finalizer first
reduces 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 be the unit in the last place of the result . Since
, and since
for the half-way algorithms (HalfUp,
HalfDown, HalfEven) and for the directed algorithms (Down, Up,
Ceiling, Floor) and for ZeroFiveUp,
and since gives ,
The bound is the decimal unit roundoff of the
standard model ,
, in which is an arithmetic operation,
its rounded result and 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 digits are removed and Inexact
whenever a removed digit was nonzero ().
The full proofs of this bound and of the other rounding facts on this page are in the attachment:
Subnormal results and
Let be the least adjusted exponent of a normal number in the context, and the least exponent a result may have (GDA 1.70, page 11 (Normal numbers, subnormal numbers and Underflow)). If the exact result has , where is its adjusted exponent, it is tiny. A tiny result may still need the unit at most, so the rounding position is not “keep digits” but “keep the digits at or above ”. With an exact coefficient of digits and exponent , rounding to digits would give the exponent ; when that is below the finalizer instead removes digits, possibly all of them, in one rounding.
A longer coefficient whose exponent is below but whose
magnitude is normal is rounded once to digits; rounding it to the
subnormal grid first would round twice. In decimal32 (,
), is
4.500005E-90.
The absolute error is then bounded by the subnormal unit,
but the relative error is not bounded by any more: the precision of the value falls gradually from digits to 1 as drops from to .
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 (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 (GDA 1.70, page 12 (Normal numbers, subnormal numbers and Underflow), gives the
exponent). Because tininess is decided before rounding, a result such as
at , 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 ).
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 but
is representable as a value but not as a triple. Here
is the adjusted exponent of the result, is the number of digits of its
coefficient , and is the largest
exponent a triple of at most digits can have. Since
means , padding the coefficient with
zeros gives
so the padded triple has at most 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 .
Overflow
If the rounded result has the operation overflows:
Overflow, Inexact and Rounded are raised and the result is either
or the largest finite number of the same sign,
. Which one follows from
treating as the representable number beyond 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 . The algorithms Down and ZeroFiveUp
move towards zero, so they stop at : ZeroFiveUp would round away
from zero only from a last digit 0 or 5, and the last digit of is 9.
With Ceiling the result is for a positive and for a
negative overflow, and with Floor it is the mirror image (in the source: overflow_to_infinity):
| Rounding | positive overflow | negative overflow |
|---|---|---|
HalfEven, HalfUp, HalfDown, Up | ||
Down, ZeroFiveUp | ||
Ceiling | ||
Floor |
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 be the thirteen flags and let
be the five invalid-family flags. For a set of
raised flags and a signal ,
which is GdaFlags::contains. An operation takes operands and a
context and is then the state machine
where is the result and the raised flags computed from the operands and the policy (precision, rounding, exponent range, clamp, extended) alone,
and is the first signal in the precedence list InvalidOperation,
DivisionByZero, Overflow, Underflow, Subnormal, Inexact, Rounded, Clamped,
LostDigits with and , or 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:
- The value does not depend on the flags or the traps. and are
functions of ; the flags and the traps only enter and
. Enabling a trap therefore never changes a result, and
Trappedcan carry the defined result. - The flags of the context are monotone and idempotent. , and since 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.
- 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:
- 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
.decTestrunner infrontend/gda_exprdoes 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 . 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:
| Aspect | decimal_gda (GDA 1.70) | decimal (IEEE 754-2019) |
|---|---|---|
| Precision | any per context | the format’s (or a chosen one) |
| Rounding | eight rounding algorithms (GDA 1.70, pages 13 and 14 (Abstract representation of context)), including HalfUp, HalfDown, ZeroFiveUp | the rounding-direction attributes (IEEE 754-2019 4.3) |
| Conditions | flags in the context that stay raised until cleared, traps with defined results | per-operation flags returned with the value |
Detailed invalid conditions, LostDigits, subset arithmetic | yes | no |
| Tininess | before rounding | before rounding |
| Elementary functions | sqrt, exp, ln, log10, power | the IEEE recommended set |
| Interchange | DPD | DPD 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 ;
- the exact result is a nonzero integer below with at most digits;
- its adjusted exponent lies in ;
- 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
is the value of the general path and 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 and be the operands of an addition, and write and for the exponent and the adjusted exponent of . When is much smaller, , the exact sum need not be formed. Every digit of lies below the last retained digit of , so influences the rounding only through its sign and its comparison with half a unit:
where and 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 replaced by a sticky
representative of the same comparison class. The implementation evaluates
exactly that (in the source: exact_base_small_addend_result), comparing
with exactly. The case where is a power of ten and has the
opposite sign (the unit below is ten times smaller) is excluded and
takes the general path.
The shortcut returns the overflow of rounded alone only when the sum overflows as well, because overflow is judged on the rounded sum (see Overflow). That holds in two cases:
- has the sign of , so the sum is larger in magnitude;
- and , so the sum is more than .
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 is
9, not an overflow. A non-extended context rounds the operands first, so the
shortcut is unchanged there.
The argument needs itself to end at or above the last retained
position, so this shortcut is taken only when fits the context exactly
(and not under ZeroFiveUp, whose rounding depends on the last kept digit).
When has digits below that position, or is exactly a midpoint, can
still move the sum across a boundary that the comparison with does not
see. An extended context then replaces by a sticky unit, as the
decimal package does. Let be the target exponent of alone and
. Every digit of and every rounding boundary of
the sum lies on the grid . The boundaries are the grid , its
midpoints, and the grid with its midpoints, which a cancellation
can reach. If , the sum lies strictly between the same two
neighbours on that grid as , with the sign of . 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 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 , so no operand is absorbed;
- the nonzero exact sum has adjusted exponent in , so that after a possible carry into a digit beyond it can neither overflow nor be subnormal, and its exponent is not clamped.
The result is then the exact aligned sum rounded once to digits at the
exponent 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
GdaFlagsandDecimalFlagsare 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
, 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 digits at the exponent plus the digits
discarded.
A quotient is formed in four steps. Let and be the coefficients of dividend and divisor, with and digits, and (a meaning of local to this section).
- Divide by once. The quotient has at least digits.
- Round it with
ZeroFiveUp, so that a nonzero remainder leaves the last digit off 0 and 5 (see Rounding to precision). - Round the result once to digits.
- Raise
roundedandinexact.
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 whatever 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 ,
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 , and exact divisions by powers of ten and by
small exact divisors separately. Every other quotient takes three steps. Let
and be the coefficients of the dividend and the divisor, and the
precision of the context.
- Scale the dividend by with . The scaled quotient is . Since and , the quotient satisfies , so has at least integer digits.
- Round to an integer with
ZeroFiveUp, the rounding algorithm of Rounding to precision; the tie it prevents is shown in the example of the half-way algorithms. - Round to digits with the rounding of the context.
Whether the quotient terminates is decided exactly: terminates iff
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 -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
. Otherwise it is rounded once to 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 and integers , . 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 are exactly
while . At precision 1,
would give (unit ), and the second rounding would see a
tie and return 0.0004. The first rounding therefore uses ZeroFiveUp. When
it leaves a last digit other than 0 and 5. A -digit number and
a -digit midpoint both end in 0 or 5 in the unit of , so is
neither of them and lies strictly on the same side of every such point as .
The second rounding then returns for every rounding algorithm
, where is rounded to digits by . 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 , , finds 12
misrounded quotients.
Square root
The function sqrt first tries an exact root. Let be the coefficient and
the exponent of the operand. The function removes trailing zeros, makes
the exponent even and takes the integer square root of , with
, by Newton’s iteration, which updates the iterate by
. It accepts
and then pads towards the ideal exponent
within digits (GDA 1.70, page 39 (square-root)). An exact root longer than
digits is an exact result like any other, so the finalizer rounds it once,
ties included: at , 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 , the scaled radicand is , and the integer root is . The increment is decided by comparing the radicand with the square of the midpoint, which is exact in integers:
Rounding once at (not first at digits and then again at
) 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 the radicand is not an integer; the comparison
is then made as , still in integers, so no
digit of 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.
- One root decides the rounding. With and of the irrational root and , the root is exact iff . Otherwise iff , because and is an integer. The comparison with the midpoint is therefore one comparison of with .
- A non-square is recognised without taking a root of it. Write the operand as with not divisible by 10, so that is the coefficient without its trailing zeros and is plus their number. The root is a decimal iff is even and is a square. If were odd, would have to be a square, so the root would be divisible by 10, and would divide . If is even, the root is , a decimal only when is one, that is, when 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 is odd, or whose 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, , so the exponent of the result, after a carry too, is at most and no clamp folds it;
- the radicand is an integer, , that is, a coefficient of at most digits.
The result has exactly digits at the exponent ; 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 and an integer exponent , the result follows GDA 1.70, page 35
(power). If the exact power fits in digits, it is returned exactly with
exponent , where is the exponent of . Otherwise binary powering runs
at working precision digits, one digit fewer in subset
contexts, where is the number of digits of . Every product is
rounded with HalfEven, and the final product is rounded to the context.
A negative starts from a rounded 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 (negative only for a negative and an odd ), not the sign of : overflows to and to .
The reciprocal keeps the cohort of the division ( is
, not ). The reason is that the exponent of an exact power
is the one repeated multiplication gives: is
with three digits and no Rounded.
A zero exponent is decided before all of this. For a finite nonzero (and
for ), is the integer with exponent 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 , where and are the maximum exponent and the precision of the format. That is 90, 369 and 6111 for decimal32, decimal64 and decimal128, which the exponent of never reaches. Only a clamped context with , 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
and raises Clamped when it does. An exact result such as
at precision 1 and raises neither.
Error of binary powering. Write , the unit roundoff of precision for the half-way algorithms (Rounding to precision), and let , with , be the relative error of one rounding. Let the accumulator hold , where is the power of it has reached and its relative error. A squaring gives and a multiplication by gives , so and . By induction on the binary expansion, for every : the error of binary powering is that of successive roundings, although only about 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 , because its error is raised to the power . Let be the exponent of the factor in the whole bound: for and for . With ,
Error in units in the last place. The exact result satisfies for the unit in the last place of the rounded result, so a relative error is at most 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.
| Exponent | Working error, at most (units) | Final result, half-way algorithms, within (units) | Final result, directed algorithms, within (units) |
|---|---|---|---|
In subset contexts is one digit smaller, so the working error grows tenfold and the bound for the half-way algorithms becomes about unit. None of this is correct rounding: a power whose exact result lies within 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
and on the adjusted exponent of the result,
where is the adjusted exponent of . The underflow shortcut is taken
only when the upper bound is at most , so the exact power
is below . The result is then that value rounded
by the rounding algorithm of the context: zero for the half-way algorithms and
Down, and 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 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
.
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 “before any rounding”, and Underflow when the result is also inexact. The working arithmetic only sees the power rounded to digits, so when the delivered result is exactly the side of the exact power is decided separately:
- The power is recomputed at precision . Its relative error is below , since it is at most roundings of .
- The recomputed power is compared with .
- A power outside that band is subnormal exactly when it is below . While the power is inside the band, is doubled and the power recomputed, five attempts in all.
For at and the exact result
is separated at , 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 lies inside its rounding
cell. For , with the operand (the base, for power, whose exponent
is ), the evaluation has five steps.
-
The exact cases are decided first and never reach the loop. They are , , , special operands, domain errors, and the cases
powercan decide exactly:- , by
sqrt; - powers of ten and ;
- guaranteed overflow or underflow;
- exact rational powers: in lowest terms with a perfect -th power, such as . The root is taken before the power, so no intermediate is longer than the result;
- to a non-integral with an integer, which is the exact
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.
- , by
-
The input is enclosed: is converted to a binary interval at bits, the working precision of the evaluation, with directed rounding (
to_binarytowards and ), so that exactly. -
The output is enclosed:
intervalevaluates on this interval and returns an enclosure . Forlog10it divides by a cached enclosure of ; forpowerit evaluates through enclosures of . -
A candidate is certified. A decimal approximation of (the midpoint of the enclosure;
powermay use a decimal series evaluation) is rounded to the context, which gives . The candidate is only a guess that the test below certifies. The result is when the whole enclosure lies strictly inside the rounding cell of , and then the midpoint of the enclosure, which belongs to the cell, rounds to the same cell.exptherefore takes the midpoint as its candidate. When the midpoint is a binary floating-point number of enormous exponent, andexptakes the series with the same number of digits instead. The candidate is converted to 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 be the open interval of reals around that round to . For the half-way algorithms its bounds are the two midpoints between and its neighbours and below and above it. For the directed algorithms it is or . The real rounding cell of a directed algorithm is half-open, or ; the test uses the open interior, which is sufficient. The bounds and are exact decimals. Each is enclosed in binary, with the upper bound of the enclosure of and the lower bound of the enclosure of , and the result is accepted when
which proves , where is the rounding to the context. A second test rounds both bounds and of the enclosure, which are exact dyadic numbers, to the context. Since every rounding algorithm is monotone, also proves .
-
Otherwise the evaluation is refined. The working precision grows, , and the loop repeats. At most evaluations are made, where is the refinement limit of the
GdaContext(GdaContext::refinement_limit, default twelve). From the start value below the increment is , so each step multiplies the precision by about 1.5 and the last of twelve evaluations runs at roughly times the starting precision.
The starting precision is bits, where , is the number of digits of the coefficient of and is the precision of the context. Four bits per decimal digit exceed , so the input is carried without loss of decimal information and 64 guard bits remain. For arguments with in a wide, unclamped context with , a cheaper first attempt uses about bits and falls back to if it cannot certify.
The loop always stops, after at most evaluations (twelve by default). With
with_refinement_limit(None) the count is unbounded, but the loop still stops
when the working precision passes
bits (at most ), with the same certification failure, so the work and the
memory stay bounded.
The loop certifies a result whenever 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 stays at a positive distance from every rounding boundary.
For exp, ln and log10 the condition on holds for every operand
that step 1 leaves. Representable numbers and midpoints are rational, so it is
enough that is irrational:
- For
exp, is rational and not 0. By the Lindemann–Weierstrass theorem is transcendental, hence irrational. - For
ln, is rational and not 1. If were rational, it would be nonzero, and would be transcendental by the same theorem, which a rational is not. So is irrational. - For
log10, 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 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 , so no fold-down is left
to report, whatever route computed it (a square root for the exponent ,
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 digits with Inexact and Rounded in every rounding algorithm,
as power.decTest rows powx2039 and powx2040 show for in ceiling.
exp, ln, log10 and power with a non-integer exponent accept only
contexts with , and 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 or
an array of base- 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:
| Target | Karatsuba mul / square | Toom-3 | first NTT mul / square | Burnikel–Ziegler | Newton division |
|---|---|---|---|---|---|
| native | 96 / 48 | 1,152 | 1,728 / 640 | from 2,816 | off |
| LLVM | 96 / 96 | 2,048 | 4,096 / 2,048 | 2,048 | 4,096 |
| Wasm, Wasm-GC, JS | 96 / 96 | 4,096 | 8,192 / 4,096 | 2,048 | 4,096 |
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 digits is correctly rounded: it is the exact result rounded once, to the returned result . Let be the unit in the last place of . Then in the half-way algorithms and in the directed algorithms andZeroFiveUp, and 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 of an operation on in the context depends on only through its policy (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;
Trappedcarries the same value asCompletedwould. - Proof before return. A finite inexact result of
exp,ln,log10or non-integerpoweris 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 andInvalidOperation. - Total order.
compare_totalis a total order on triples (sign, then class, then value, then exponent, then payload), andDecimal::compareis a total preorder in which NaNs form one class above all other values. - Checked results. The pinned
officialtest suite and the legacyofficial0suite 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 , is part of a finite number in GDA.
reduceremoves 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
.decTestfiles, run test suites or read files; that isfrontend/gda_exprand 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.
ParseCheckedis a value-only adapter over the GDA to-number conversion. It mapsArithmeticContextto the engine context, so the precision, the rounding, the exponent limits and the clamp apply. The returnedResultcannot carry the flags or traps of GDA; a caller that needs them usesto_numberwith aGdaContext.- It stores no exponent beyond the implementation limit on the exponents of a stored value: a finite number needs an exponent of at least and an adjusted exponent of at most , 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
-
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
dectestcollection, version 2.62. ↩ -
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
-
This is decNumber’s
DEC_ROUND_05UPdevice; GDA 1.70, page 14 (Abstract representation of context) givesround-05upfor the same purpose, arithmetic at shorter lengths without double rounding. With the rounding of the context in the first rounding, a sweep of , , finds 12 misrounded quotients. ↩ -
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. ↩