decimal_checked tutorial
This tutorial shows how to run an IEEE decimal calculation as one pipeline that
remembers every exceptional condition: you fix a DecimalContext, start a
DecimalChecked from a string or number, apply operations, and at the end read
the value together with the union of all flags raised on the way. The typical
use is an auditable calculation (money, measurements) where “was anything
rounded?” or “did anything overflow?” must be answered for the whole
computation, not for the last step. Arithmetic comes from
decimal; the design page gives
the algebra of flag accumulation; the API reference
lists every method.
| I want to | Use |
|---|---|
| start a pipeline from text or a number | DecimalChecked::parse, from_int |
| know whether any step rounded | flags() |
| see what only the last step did | raised() |
| continue after a division by zero | flagged values |
| start a new audit period | clear_flags |
call ln, exp or pow in a pipeline | a bounded context |
use an ArithmeticContext | from_arithmetic_context |
| hand the result to the contextual traits | result() |
Quick start
Add floating to your module:
moon add Luna-Flow/floating@0.11.0
and import both packages in your moon.pkg:
import {
"Luna-Flow/floating/decimal",
"Luna-Flow/floating/decimal_checked",
}
Divide 10 by 4 in decimal64 and check that the result is exact:
///|
test "quick start: an exact division" {
let ctx = @decimal.DecimalContext::decimal64()
let r = @decimal_checked.DecimalChecked::from_int(10, ctx).div(
@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::from_int(4), ctx),
)
inspect(r.value().to_string(), content="2.5")
inspect(r.flags().inexact(), content="false")
}
Everyday tasks
The examples list flags with this helper:
///|
fn flags(f : @decimal.DecimalFlags) -> String {
let named = [
("inexact", f.inexact()),
("invalid_operation", f.invalid_operation()),
("division_by_zero", f.division_by_zero()),
("overflow", f.overflow()),
("underflow", f.underflow()),
]
[ for p in named if p.1 => p.0 ].join(",")
}
Audit a price calculation
Compute a price with tax, rounded to cents. raised() describes the last step
and flags() the whole pipeline:
///|
test "price with tax" {
let ctx = @decimal.DecimalContext::decimal64()
let gross = @decimal_checked.DecimalChecked::parse("19.99", ctx)
.mul(@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::from_string("1.0825").unwrap(), ctx))
.quantize(@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::from_string("0.01").unwrap(), ctx))
inspect(gross.value().to_string(), content="21.64")
inspect(flags(gross.raised()), content="inexact")
inspect(flags(gross.flags()), content="inexact")
}
The multiplication is exact (); only the quantization to cents rounds, and the pipeline records that.
Find out that an earlier step rounded
Flags of earlier steps stay in flags() even when later steps are exact:
///|
test "an early rounding is remembered" {
let ctx = @decimal.DecimalContext::new(precision=5, e_max=100)
let r = @decimal_checked.DecimalChecked::parse("1.234567", ctx)
.add(@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::from_int(1), ctx))
.mul(@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::from_int(2), ctx))
inspect(r.value().to_string(), content="4.4692")
inspect(flags(r.raised()), content="")
inspect(flags(r.flags()), content="inexact")
}
Keep going after a division by zero
IEEE decimal arithmetic defines a result for every operation. Dividing by zero
gives an infinity and the division_by_zero flag; the pipeline continues and
the flag is kept:
///|
test "division by zero is a flagged value" {
let ctx = @decimal.DecimalContext::decimal64()
let r = @decimal_checked.DecimalChecked::from_int(1, ctx)
.div(@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::zero(), ctx))
.add(@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::from_int(5), ctx))
inspect(r.value().to_string(), content="inf")
inspect(flags(r.flags()), content="division_by_zero")
inspect(r.is_ok(), content="true")
}
Decide at the end what the flags mean for your application, for example with
DecimalFlags::has_error, which is true when any of invalid_operation,
not_computed or division_by_zero is set.
Start a new audit period
clear_flags resets both the raised and the accumulated flags without
touching the value:
///|
test "clear flags between phases" {
let ctx = @decimal.DecimalContext::decimal64()
let phase1 = @decimal_checked.DecimalChecked::from_int(2, ctx).div(
@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::from_int(3), ctx),
)
inspect(flags(phase1.flags()), content="inexact")
let phase2 = phase1.clear_flags().mul(
@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::from_string("1E+1").unwrap(), ctx),
)
inspect(phase2.value().to_string(), content="6.666666666666667")
inspect(flags(phase2.flags()), content="")
}
Multiplying the 16-digit quotient by 1E+1 is exact and its exponent fits, so
the second phase reports no flags although the first one was inexact.
Going further
Elementary functions need a bounded context
Mathematical functions (exp, ln, pow, the trigonometric family, …)
follow the General Decimal Arithmetic restriction to precision and exponent
limits within . Use one of the interchange contexts or explicit
bounds; with a range above 999,999 they return NaN with
invalid_operation:
///|
test "a bounded context for ln" {
let good = @decimal_checked.DecimalChecked::from_int(
10,
@decimal.DecimalContext::decimal128(),
).ln()
inspect(good.value().to_string(), content="2.302585092994045684017991454684364")
let bad = @decimal_checked.DecimalChecked::from_int(
10,
@decimal.DecimalContext::new(precision=34, e_max=999_999_999),
).ln()
// not computed (a context beyond the kernels): the error, not an invalid_operation flag
inspect(bad.error().unwrap().is_certification_failure(), content="true")
}
Start from a Luna-Flow/arithmetic context
Code that is generic over Luna-Flow/arithmetic carries an
ArithmeticContext. DecimalContext::from_arithmetic_context maps its
precision, rounding direction and exponent bounds (clamp is ignored: every
IEEE format clamps); the predefined
ArithmeticContext::decimal64() maps to the same context as
DecimalContext::decimal64():
///|
test "from an arithmetic context" {
let ctx = @decimal.DecimalContext::from_arithmetic_context(
@lf_arith.ArithmeticContext::decimal64(),
).unwrap()
inspect(ctx == @decimal.DecimalContext::decimal64(), content="true")
let r = @decimal_checked.DecimalChecked::from_int(2, ctx).sqrt()
inspect(r.value().to_string(), content="1.414213562373095")
}
Hand the result to the contextual traits
result() returns Ok((value, flags)) or the recorded error. The
AddContextual, SqrtContextual, … implementations of Decimal in
Luna-Flow/arithmetic report diagnostics instead of flags; the shared
conditions that decimal has (inexact, overflow, underflow) can be
carried over field by field:
///|
fn diagnostics(f : @decimal.DecimalFlags) -> @lf_arith.ArithmeticDiagnostics {
@lf_arith.ArithmeticDiagnostics::new(
inexact=f.inexact(),
overflow=f.overflow(),
underflow=f.underflow(),
)
}
///|
test "accumulated flags become arithmetic diagnostics" {
let ctx = @decimal.DecimalContext::decimal64()
match @decimal_checked.DecimalChecked::from_int(1, ctx).div(@decimal_checked.DecimalChecked::from_decimal(@decimal.Decimal::from_int(3), ctx)).result() {
Ok((value, f)) => {
let outcome = @lf_arith.ArithmeticOutcome::with_diagnostics(value, diagnostics(f))
inspect(outcome.diagnostics.inexact, content="true")
}
Err(e) => fail(e.message)
}
}
The design page shows why converting the accumulated flags once gives the same diagnostics as combining the per-step diagnostics.
Common pitfalls
raised()is not the whole story. It describes the latest step only; audit withflags().- Exceptional results are not errors. NaN, infinities and rounded values
are successes with flags.
is_err()is true only for certification failures of elementary functions. - Wide contexts disable the mathematical functions. See above; this
applies to an
e_maxabove 999,999. - Binary sources.
from_double(0.1, …)converts the binary value of0.1rounded to 17 digits, not one tenth and not the exact binary value (in decimal128 it is0.10000000000000001); parse the string"0.1"instead. remainderis the IEEE remainder. It rounds the quotient to the nearest integer, so1remainder0.6is-0.2, not0.4.- The right operand is a pipeline. Lift a plain value with
DecimalChecked::from_decimal(x, ctx), which rounds it intoctxfirst (a signaling NaN is quieted and raisesinvalid_operation); the operation then runs in the context of the left pipeline and rounds the result. The conditions of the right pipeline join the result, and its error stops the operation. To use the operand exactly (IEEE 754-2019 5.1: operands exact, one rounding), lift it in a context wide enough to hold it, such asdecimal128; lifting at the precision of the left pipeline rounds twice. At three digits,1.00 + 0.24500001is1.25with a wide lift and1.24with a lift at three digits (the operand becomes0.245withinexact). clear_flagsalso works after an error, but the error stays.
Next steps
decimal_checkeddesign: the state model, the flag monoid and the short-circuit rule.decimal_checkedAPI: every method.decimaltutorial: contexts, rounding modes and interchange formats.decimal_gda_checkedtutorial: the same idea for General Decimal Arithmetic with sticky status and traps.