decimal 教程
本教程展示如何使用行为与人们书写方式一致的十进制数进行计算:0.1 + 0.2 恰好等于 0.3,12.30 记得自己有两位小数,每一次舍入都由你选择并向你报告。你将解析和格式化值,在上下文下计算并读取其标志,用 quantize_ctx 对金额舍入,交换 decimal64 位模式,并调用经过认证的初等函数。每一步背后的数学见 decimal 设计;每个函数都在 decimal API 中有规定。
| 我想要 | 使用 |
|---|---|
| 解析金额并保留其小数位数 | Decimal::from_string |
| 以固定精度计算并查看哪些被舍入 | *_ctx 运算与 DecimalFlags |
| 把金额舍入到分,采用 half-even 或 half-up | quantize_ctx |
| 获得有保证的下界和上界 | 定向舍入 |
| 读写 decimal64 位模式(DPD 或 BID) | DecimalInterchange |
| 求对数或指数 | ln_ctx, try_ln_ctx |
在十进制数上运行泛型 Ring 代码 | 代数 trait |
| 确定性地对存储的值排序 | total_order_compare |
| 在长流水线中累积标志 | decimal_checked |
快速入门
把 floating 加入你的模块:
moon add Luna-Flow/floating@0.11.0
然后在你的 moon.pkg 中导入该包:
import {
"Luna-Flow/floating/decimal",
}
最小的实用程序把两个 Double 无法表示的十进制小数相加:
///|
test "decimal quick start" {
let a = @decimal.Decimal::from_string("0.1").unwrap()
let b = @decimal.Decimal::from_string("0.2").unwrap()
inspect(a + b, content="0.3")
inspect(0.1 + 0.2 == 0.3, content="false")
}
0.1 是 ,而 2 的幂都不能被 5 整除,因此二进制浮点只能近似它;十进制浮点则能精确存储它。
日常任务
解析金额并保留其小数位数
解析会保留文本中的指数。两个值可以相等却携带不同的信息:
///|
test "decimal parsing keeps the exponent" {
let price = @decimal.Decimal::from_string("12.30").unwrap()
let same = @decimal.Decimal::from_string("12.3").unwrap()
inspect(price == same, content="true")
inspect(price.exponent10(), content="-2")
inspect(same.exponent10(), content="-1")
inspect(price.same_quantum(same), content="false")
inspect(price.normalized(), content="12.3")
}
12.30 和 12.3 是同一个同值类(cohort)的两个成员:数值相等,但以不同的指数书写。normalized() 选取最短的成员。不要对小数位数有意义的金额调用它;需要规范键时才调用它。
整数以约简形式构造:Decimal::from_int(1000) 存储为 ,打印为 1E+3。需要四位数字时请解析 "1000"。
在上下文下计算并保留标志
DecimalContext 确定精度、舍入方向和指数范围。每个 *_ctx 运算都返回结果及其引发的标志。边计算边合并标志:
///|
test "decimal64 pipeline with flags" {
let ctx = @decimal.DecimalContext::decimal64()
let d = fn(s : String) { @decimal.Decimal::from_string(s).unwrap() }
let (total, f1) = d("100").div_ctx(d("3"), ctx)
let (scaled, f2) = total.mul_ctx(d("3"), ctx)
let flags = f1.combine(f2)
inspect(total, content="33.33333333333333")
inspect(scaled, content="99.99999999999999")
inspect(flags.inexact(), content="true")
inspect(flags.has_error(), content="false")
}
inexact 告诉你 没有被精确计算;它不是错误,因此 has_error() 仍为 false。has_error() 报告无效运算、无法解析的文本、除以零、不可能的除法和无效上下文。当你的应用关心 overflow、underflow、inexact 这些标志时,请逐个检查。
用 quantize_ctx 对金额舍入
quantize_ctx 让一个值取得模板值的指数。在上下文中选择舍入模式;商业舍入是 RoundTiesToAway:
///|
test "decimal round to cents" {
let d = fn(s : String) { @decimal.Decimal::from_string(s).unwrap() }
let cents = d("0.01")
let bankers = @decimal.DecimalContext::decimal64()
let commercial = @decimal.DecimalContext::new(
precision=16,
e_max=384,
rounding=@decimal.DecimalRoundingMode::RoundTiesToAway,
)
inspect(d("2.345").quantize_ctx(cents, bankers).0, content="2.34")
inspect(d("2.345").quantize_ctx(cents, commercial).0, content="2.35")
inspect(d("7").quantize_ctx(cents, bankers).0, content="7.00")
}
半偶(“银行家”)舍入把平局 2.345 送到末位为偶数的 4;半上舍入则把它送向远离零的方向。quantize_ctx 从不悄悄选择另一个指数:如果结果所需的位数超过精度,你会得到带 invalid_operation 的 NaN。
转换为整数
to_int_ctx、to_int64_ctx、to_uint_ctx 和 to_uint64_ctx 按上下文的方向舍入为定宽整数,对 NaN、无穷或超出范围的值返回 None 并带 invalid_operation。传入 exact=true,舍入改变了值时就会得到 inexact:
///|
test "decimal convert to integer" {
let d = fn(s : String) { @decimal.Decimal::from_string(s).unwrap() }
let bankers = @decimal.DecimalContext::decimal64()
let (value, flags) = d("2.5").to_int_ctx(bankers, exact=true)
debug_inspect(value, content="Some(2)")
assert_true(flags.inexact())
let (negative, flags) = d("-1").to_uint_ctx(bankers)
debug_inspect(negative, content="None")
assert_true(flags.invalid_operation())
debug_inspect(
d("9223372036854775807").to_int64_ctx(bankers).0,
content="Some(9223372036854775807)",
)
}
在格式之间转换
convert_format 把值移到另一个十进制交换格式,to_binary_ctx 和 from_binary_ctx 则跨到二进制格式以及从二进制格式回来,都带有舍入的标志:
///|
test "decimal convert between formats" {
let d = fn(s : String) { @decimal.Decimal::from_string(s, precision=34).unwrap() }
let (narrow, flags) = d("1.2345678901234567").convert_format(Decimal32)
inspect(narrow, content="1.234568")
assert_true(flags.inexact())
let (bits, flags) = d("0.1").to_binary_ctx(@binary.BinaryContext::binary32())
assert_true(flags.inexact())
inspect(bits.to_hex(), content="0xcccccdp-27")
let (back, _) = @decimal.Decimal::from_binary_ctx(
@binary.Binary::from_double(0.5),
@decimal.DecimalContext::decimal64(),
)
inspect(back, content="0.5")
}
从两侧界定结果
定向舍入给出有保证的界。把同一个商分别向 和向 舍入,即可夹住精确值:
///|
test "decimal directed rounding brackets the exact quotient" {
let ctx = @decimal.DecimalContext::decimal32()
let one = @decimal.Decimal::one()
let seven = @decimal.Decimal::from_int(7)
let down = ctx.with_rounding(@decimal.DecimalRoundingMode::RoundTowardNegative)
let up = ctx.with_rounding(@decimal.DecimalRoundingMode::RoundTowardPositive)
inspect(one.div_ctx(seven, down).0, content="0.1428571")
inspect(one.div_ctx(seven, up).0, content="0.1428572")
}
两个结果是相邻的 decimal32 值, 严格位于它们之间。
交换 decimal64 位模式
交换格式是数据库、文件和其他语言之间交换数据所用的格式。请用对方期望的编码进行编码,并用同一编码解码:
///|
test "decimal64 DPD and BID round trip" {
let fmt = @decimal.DecimalInterchangeFormat::Decimal64
let price = @decimal.Decimal::from_string("19.99").unwrap()
let (bits, flags) = @decimal.DecimalInterchange::from_decimal_with_encoding(
price,
fmt,
@decimal.DecimalInterchangeEncoding::BID,
)
inspect(bits.to_hex(), content="#31800000000007CF")
inspect(flags.has_error(), content="false")
inspect(bits.to_decimal(), content="19.99")
let (dpd, _) = price.to_interchange_hex(fmt)
inspect(dpd, content="#22300000000004FF")
}
两种编码都保留指数,因此 19.99 读回时仍有两位小数。不是你自己产生的位模式可能是非规范的;把它们保存在 DecimalInterchange 中,并在比较位模式之前调用 canonical()。
调用初等函数
对数、指数、非整数指数的幂和三角函数是经过认证的:结果是在每种舍入方向下正确舍入的值,或是一个明确的失败(整数指数的幂由精确的幂或由细化的定向界一次舍入得到,不经认证)。对普通操作数,它们需要一个 e_max 至多为 999,999、e_min 至少为 -999,999、且精度在初等函数精度上限之内(默认 999,999 位)的上下文,例如某个格式预设;NaN、无穷、零以及 IEEE 754-2019 9.2.1 的精确点在每个上下文中都是值:
///|
test "decimal certified logarithm" {
let ctx = @decimal.DecimalContext::decimal64()
let two = @decimal.Decimal::from_int(2)
match two.try_ln_ctx(ctx) {
Ok((value, flags)) => {
inspect(value, content="0.6931471805599453")
inspect(flags.inexact(), content="true")
}
Err(e) => fail("not certified: \{e.is_certification_failure()}")
}
inspect(@decimal.Decimal::from_int(1000).log10_ctx(ctx).0, content="3")
}
try_ln_ctx 在上下文或普通操作数超出初等函数的限制时(见下面的第一条陷阱)立即返回 Err(认证失败),不做任何求值;否则只在结果无法在上下文的细化限制内认证时返回 Err(默认十二步;ctx.with_refinement_limit(Some(24)) 允许更多步,ctx.with_refinement_limit(None) 取消步数限制,代价是难舍入输入的求值更久;提高限制对第一种情形没有帮助);ln_ctx 把这两种情形都变为带 not_computed 的 NaN,而不是 invalid_operation(后者用于 IEEE 754 定义为无效的结果)。 这类精确结果返回时不带 inexact。
对于很小的增长率或很小的指数,请使用保留零附近部分的函数,而不要计算 exp2(x) - 1 或 log2(1 + x):后者在舍入 时会丢失 的数字。exp2m1_ctx、exp10m1_ctx、log2p1_ctx 与 log10p1_ctx 直接由 计算 、、 与 :
///|
test "decimal growth near zero" {
let ctx = @decimal.DecimalContext::decimal64()
let rate = @decimal.Decimal::from_string("1E-12").unwrap()
// log10(1 + 1E-12): 1 + 1E-12 would need 13 digits of a 16-digit result.
inspect(rate.log10p1_ctx(ctx).0, content="4.342944819030347E-13")
inspect(rate.exp10m1_ctx(ctx).0, content="2.302585092996697E-12")
// An integer argument gives an exact result.
inspect(@decimal.Decimal::from_int(10).exp2m1_ctx(ctx).0, content="1023")
}
复利就是 compound_ctx:对整数个期数计算 ,直接由利率本身计算;当幂是较短的十进制数时结果精确,并保持利率的小数位:
///|
test "decimal compound interest" {
let ctx = @decimal.DecimalContext::decimal64()
let rate = @decimal.Decimal::from_string("0.05").unwrap()
inspect(rate.compound_ctx(3, ctx).0, content="1.157625")
// Present value of one unit due in 3 periods.
inspect(rate.compound_ctx(-3, ctx).0, content="0.8638375985314761")
}
以半圈为单位度量角度可以避开舍入后的 值:atan2pi_ctx 把一个点的方向表示为半圈的几分之几,四分之一圈是精确的。
///|
test "decimal angles in half-revolutions" {
let ctx = @decimal.DecimalContext::decimal64()
let d = fn(s : String) { @decimal.Decimal::from_string(s).unwrap() }
// The point (-2, 2) is 3/4 of a half turn from the positive x-axis.
inspect(d("2").atan2pi_ctx(d("-2"), ctx).0, content="0.75")
// The point (-1, 3) is not on a quarter turn: the result is rounded.
inspect(d("3").atan2pi_ctx(d("-1"), ctx).0, content="0.6024163823495667")
}
深入了解
基于代数 trait 的泛型代码
Decimal 通过其普通运算符实现了 luna-generic 的 Ring,因此泛型代码无需修改即可在其上运行:
///|
fn[T : @lf_alg.Ring] dot(xs : Array[T], ys : Array[T]) -> T {
let mut acc : T = @lf_alg.Zero::zero()
for i in 0..<xs.length() {
acc = acc + xs[i] * ys[i]
}
acc
}
///|
test "decimal in generic ring code" {
let d = fn(s : String) { @decimal.Decimal::from_string(s).unwrap() }
inspect(dot([d("1.5"), d("2.25")], [d("4"), d("0.2")]), content="6.450")
}
普通运算符没有上下文参数:每个运算符都是对应的 *_ctx 运算在一个私有上下文(取较大的操作数精度,默认 34 位)中的结果,半值取偶舍入,采用值的存储范围,并返回 IEEE 754-2019 所要求的同值类成员(1.20 + 3.40 是 4.60)。需要精度、指数范围或标志的代码应接收一个 DecimalContext 并调用 *_ctx 运算。
共享的 contextual trait
针对 Luna-Flow/arithmetic 编写的代码使用 ArithmeticContext,并得到带诊断信息的 ArithmeticOutcome:
///|
test "decimal through the contextual traits" {
let ctx = @lf_arith.ArithmeticContext::new(5)
let x = @decimal.Decimal::from_int(2)
match x.div_contextual(@decimal.Decimal::from_int(3), ctx) {
Ok(outcome) => {
inspect(outcome.value, content="0.66667")
inspect(outcome.diagnostics.inexact, content="true")
}
Err(_) => fail("unexpected error")
}
inspect(x.div_contextual(@decimal.Decimal::zero(), ctx) is Err(_), content="true")
}
错误(invalid_operation、division_by_zero……)变为 Err;不精确和范围事件变为诊断信息。
流水线、GDA 状态与区间
decimal_checked包装一个值、它的上下文及其累积的标志,因此长流水线无需显式调用combine。decimal_gda实现了带粘滞状态和陷阱的通用十进制算术模型。它的值是一个独立的类型;当你需要.decTest的行为而不是 IEEE 的逐运算标志时,请使用它。- 要把十进制值包络在二进制区间中,可分别用
to_binary(precision=p, mode=RoundTowardNegative)和to_binary(precision=p, mode=RoundTowardPositive)转换两次,再以这两个界构造一个interval区间。
用于存储的确定性顺序
total_order_compare 对每种表示(包括同值类、带符号零和 NaN)都给出顺序,因此它是对存储值排序或对逐位相同的记录去重的合适键:
///|
test "decimal total order separates cohorts" {
let d = fn(s : String) { @decimal.Decimal::from_string(s).unwrap() }
let xs = [d("1.0"), d("-0"), d("1.00"), d("NaN"), d("0")]
xs.sort_by(fn(a, b) { a.total_order_compare(b) })
inspect(xs.map(fn(x) { x.to_string() }).join(" "), content="-0 0 1.00 1.0 nan")
}
常见陷阱
- 初等函数需要不超过 999,999 的指数范围。
DecimalContext::new()是格式 ,初等函数接受它;e_max超过 999,999 的上下文,或精度为 1000 位及以上且使用默认范围的上下文,会使它们对普通操作数返回带not_computed的 NaN(精度限制默认为 999,999 位,是上下文的字段:ctx.with_elementary_precision_limit(None)取消它,不保证运行时间和内存)(不是invalid_operation,后者用于 IEEE 754 定义为无效的结果)。IEEE 754-2019 §9.2.1 的特殊操作数和精确点(ln_ctx(1)、exp_ctx(-inf)、sin_ctx(0))在每个上下文中都是值。请使用decimal32()/decimal64()/decimal128(),或传入不超过 999,999 的e_max。 - 运算符不是上下文运算。 它们按半值取偶舍入到较大的操作数精度,且只应用值的存储范围,因此超出该范围的结果是无穷或零。当结果必须受某个格式约束、以其他模式舍入或通过标志报告时,请使用
mul_ctx和div_ctx。 ==不是 IEEE 相等。Eq和compare把每个 NaN 视为与每个 NaN 相等且大于每个数,这样排序才能正常工作。当 NaN 必须无序时,请使用compare_checked或is_nan。has_error()的范围很窄。 它忽略inexact、overflow和underflow。当这些标志重要时,请自行检查,例如在长乘积之后检查overflow。- checked 幂运算按上下文精度转换指数。
pow_int_checked和pow_nat_checked会把整数指数转换为具有上下文精度的Decimal,因此位数超过精度的指数会在求幂之前被舍入。请保持 ,或调用会精确转换指数的pown_ctx。 - 上下文拥有 IEEE 754-2019 §4.3 的五种舍入方向属性,仅此而已。 GDA 的
HalfDown、Up和ZeroFiveUp只在decimal_gda中;商业舍入是RoundTiesToAway。 - 二进制转换会丢失十进制含义。
from_double(0.1)是精确的二进制值0.1000000000000000055511151231257827(舍入到 34 位),而不是0.1;请改为解析文本。
后续步骤
- decimal API:每个类型和函数及其精确语义。
- decimal 设计:格式、同值类、编码、舍入、误差界与认证。
- decimal 符合性和 decimal 性能:有限的证据与测量方法。
- 关于流水线与 GDA 状态,见
decimal_checked教程和decimal_gda教程。