decimal_checked 教程
本教程展示如何把一次 IEEE 十进制计算作为一条记住每个异常情形的流水线来运行:你确定一个 DecimalContext,从字符串或数开始一个 DecimalChecked,依次应用运算,最后读取值以及途中引发的所有标志的并集。典型用途是可审计的计算(金额、测量值),其中“是否有任何舍入?”或“是否有任何上溢?”必须针对整个计算而不是最后一步来回答。算术来自 decimal;设计页面给出了标志累积的代数;API 参考列出了所有方法。
| 我想要 | 使用 |
|---|---|
| 从文本或数值开始一条流水线 | DecimalChecked::parse, from_int |
| 知道是否有任何步骤发生了舍入 | flags() |
| 只查看最后一步做了什么 | raised() |
| 在除以零之后继续 | 带标志的值 |
| 开始新的审计周期 | clear_flags |
在流水线中调用 ln、exp 或 pow | 有界上下文 |
使用 ArithmeticContext | from_arithmetic_context |
| 把结果交给上下文 trait | result() |
快速入门
把 floating 加入你的模块:
moon add Luna-Flow/floating@0.11.0
然后在你的 moon.pkg 中导入这两个包:
import {
"Luna-Flow/floating/decimal",
"Luna-Flow/floating/decimal_checked",
}
在 decimal64 下计算 10 除以 4,并检查结果是否精确:
///|
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")
}
日常任务
示例使用如下辅助函数列出标志:
///|
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(",")
}
审计价格计算
计算含税价格并舍入到分。raised() 描述最后一步,flags() 描述整条流水线:
///|
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")
}
乘法是精确的();只有量化到分时发生了舍入,流水线记录了这一点。
发现先前某一步发生了舍入
即使后续步骤是精确的,先前步骤的标志也会保留在 flags() 中:
///|
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")
}
除以零之后继续执行
IEEE 十进制算术为每个运算都定义了结果。除以零得到无穷和 division_by_zero 标志;流水线继续执行,标志被保留:
///|
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")
}
最后再决定这些标志对你的应用意味着什么,例如使用 DecimalFlags::has_error,只要 invalid_operation、not_computed 或 division_by_zero 中任一被设置,它就为真。
开始新的审计周期
clear_flags 同时重置最近引发的标志和累积的标志,而不改动值:
///|
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="")
}
把 16 位的商乘以 1E+1 是精确的,且其指数可容纳,因此尽管第一阶段不精确,第二阶段也不报告任何标志。
深入了解
初等函数需要有界上下文
数学函数(exp、ln、pow、三角函数族……)遵循通用十进制算术的限制,精度和指数界须在 以内。请使用某个交换格式上下文或显式的界;范围超过 999,999 时,它们会返回带 invalid_operation 的 NaN:
///|
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")
}
从 Luna-Flow/arithmetic 上下文开始
基于 Luna-Flow/arithmetic 的泛型代码携带一个 ArithmeticContext。DecimalContext::from_arithmetic_context 映射其精度、舍入方向和指数界(clamp 被忽略:每个 IEEE 格式都钳制);预定义的 ArithmeticContext::decimal64() 映射到与 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")
}
把结果交给 contextual trait
result() 返回 Ok((value, flags)) 或记录下的错误。Decimal 在 Luna-Flow/arithmetic 中的 AddContextual、SqrtContextual……实现报告的是诊断信息而不是标志;decimal 具有的共享情形(inexact、overflow、underflow)可以逐字段转移过去:
///|
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)
}
}
设计页面说明了为什么一次性转换累积的标志与合并逐步的诊断信息结果相同。
常见陷阱
raised()并不是全部。 它只描述最近一步;审计请用flags()。- 异常结果不是错误。 NaN、无穷和舍入后的值都是带标志的成功结果。
is_err()只在初等函数认证失败时为真。 - 宽上下文会禁用数学函数。 见上文;这适用于
e_max超过 999,999 的情形。 - 二进制来源。
from_double(0.1, …)转换的是0.1的二进制值舍入到 17 位数字后的结果,既不是十分之一,也不是精确的二进制值(在 decimal128 中为0.10000000000000001);请改为解析字符串"0.1"。 remainder是 IEEE 余数。 它把商舍入到最近的整数,因此1对0.6取余的结果是-0.2,而不是0.4。- 右操作数是流水线。 用
DecimalChecked::from_decimal(x, ctx)提升普通值,它会先把值舍入到ctx(信号 NaN 被静默并引发invalid_operation);运算随后在左侧流水线的上下文中运行并舍入结果。右侧流水线的条件并入结果,它的错误会终止运算。要精确使用该操作数(IEEE 754-2019 §5.1:操作数精确,只舍入一次),应在足以容纳它的上下文(如decimal128)中提升它;按左侧流水线的精度提升会舍入两次。在三位数字下,1.00 + 0.24500001宽提升为1.25,三位提升为1.24(操作数变为0.245并带inexact)。 clear_flags在出错之后也能使用, 但错误仍然保留。
后续步骤
decimal_checked设计:状态模型、标志幺半群与短路规则。decimal_checkedAPI:所有方法。decimal教程:上下文、舍入模式与交换格式。decimal_gda_checked教程:同一思路在带粘滞状态和陷阱的通用十进制算术上的应用。