internal API
用途
internal 包含供各数值核心使用的精确整数与有理数辅助函数:2、5 和 10 的幂,数字位数计数,去除尾部因子,带显式舍入模式的整数除法,十进制字符串拆分器,最简有理数,二进有理数包络,以及经认证初等函数的细化预算。它是一个内部包:无法从 Luna-Flow/floating 之外导入,其接口可能在不另行通知的情况下变更。设计页面证明舍入与包络不变式;教程展示这些辅助函数如何组合使用。
并非每个核心都使用每个辅助函数。在当前分支上,库代码的使用情况如下:
| 包 | 所用的辅助函数 |
|---|---|
decimal, decimal_gda | split_decimal_string, round_positive_div, pow5, pow10, digits10, abs_bigint, bigint_zero, bigint_one, DecimalExponentBounds, decimal_exponent_limit, CertifiedRefinementBudget, certified_failure |
binary, interval | CertifiedRefinementBudget, certified_failure |
二进制和十进制核心使用各自的内核来舍入自己的系数。其余的辅助函数(round_shift、remove_factor10、trim_trailing_decimal_zeros、exact_divide_by_power_of_ten、compare_abs 以及 CertifiedDyadic 系列)仅由本包的测试和各核心的测试使用。semantic 不再使用 internal:它自己拥有精确有理数(ExactRational)及其规范化。
十进制指数边界
DecimalExponentBounds 用于验证两个十进制核心采用的 decNumber decContext.h 限制,并在不发生 Int 回绕的情况下计算由上下文导出的指数端点。precision 必须在 1..=999,999,999 范围内,e_min 在 -999,999,999..=0 范围内,e_max 在 0..=999,999,999 范围内。GDA 1.70 未规定固定的上下文限制,并要求指数范围平衡;这里不强制该单独的平衡规则。
pub struct DecimalExponentBounds {
valid_ : Bool
etiny_ : Int
etop_ : Int
}
pub fn DecimalExponentBounds::new(Int, Int, Int) -> Self
pub fn DecimalExponentBounds::is_valid(Self) -> Bool
pub fn DecimalExponentBounds::etiny(Self) -> Int
pub fn DecimalExponentBounds::etop(Self) -> Int
对于有效输入,etiny 为 ,etop 为 。对于无效输入,is_valid() 返回 false;为使此内部值对所有输入都有定义,返回的端点仅会在必要时钳制,调用方必须先拒绝无效上下文,不能使用这些端点。
导入
在模块内部,将该包添加到 moon.pkg 中:
import {
"Luna-Flow/floating/internal",
}
示例以 @internal. 调用该包,以 @lf_arith. 调用 Luna-Flow/arithmetic;BigInt 字面量写作 12N。接口将 Luna-Flow/arithmetic 显示为 @arithmetic(RoundingMode、ArithmeticError、CertificationStage、CertificationFailureReason),并使用 @def.Sign。
整数基础
bigint_zero, bigint_one
这些函数返回 BigInt 常量 和 。
pub fn bigint_zero() -> @bigint.BigInt
pub fn bigint_one() -> @bigint.BigInt
abs_bigint, compare_abs
abs_bigint(x) 为 ,compare_abs(a, b) 比较 与 。
pub fn abs_bigint(@bigint.BigInt) -> @bigint.BigInt
pub fn compare_abs(@bigint.BigInt, @bigint.BigInt) -> Int
compare_abs 返回负数、零或正数的 Int(即对两者绝对值调用 BigInt::compare 的结果)。
///|
test "integer basics" {
inspect(@internal.abs_bigint(-7N), content="7")
inspect(@internal.compare_abs(-3N, 2N) > 0, content="true")
}
幂
pow5, pow10
这些函数返回 和 。
pub fn pow5(Int) -> @bigint.BigInt
pub fn pow10(Int) -> @bigint.BigInt
当 时它们会中止。pow5 和 pow10 读取一个进程级缓存,该缓存初始包含 的幂,并按需扩展到至多 ;更大的幂每次都重新计算,不做缓存。
digits10
digits10(x) 是 的十进制位数,且 digits10(0) == 1。
pub fn digits10(@bigint.BigInt) -> Int
对于 ,它返回满足 的唯一 :先根据位长给出估计,再通过与 10 的幂比较加以修正(不构造十进制字符串)。
///|
test "powers and digit counts" {
inspect(@internal.pow5(3), content="125")
inspect(@internal.digits10(0N), content="1")
inspect(@internal.digits10(-999N), content="3")
inspect(@internal.digits10(@internal.pow10(5000)), content="5001")
}
尾部因子
remove_factor10
remove_factor10(coeff, exp) 从 coeff 中去除所有因子 10,并相应调整十进制指数。
pub fn remove_factor10(@bigint.BigInt, Int) -> (@bigint.BigInt, Int)
值 和符号保持不变,且新的系数不能被 10 整除。零得到 。
trim_trailing_decimal_zeros
trim_trailing_decimal_zeros(coeff, exp, max_drop?) 去除至多 max_drop 个十进制尾随零。
pub fn trim_trailing_decimal_zeros(@bigint.BigInt, Int, max_drop? : Int) -> (@bigint.BigInt, Int, Int)
它返回 ,满足 、,且 在 max_drop 的约束下取最大。负的 max_drop(默认 )将限制设为 digits10(c) - 1,该限制永远不会起作用,因为带有 个尾随零的非零整数至少有 位数字;因此默认情况下会去除所有尾随零。零得到 。设置限制可让调用方在某个目标指数处停下,正如 decNumber 风格的、截尾到理想指数的做法那样。
exact_divide_by_power_of_ten
当除法精确时,exact_divide_by_power_of_ten(coeff, shift) 为 Some(coeff / 10^shift),否则为 None。
pub fn exact_divide_by_power_of_ten(@bigint.BigInt, Int) -> @bigint.BigInt?
符号保持不变。对于任意 shift,零都得到 Some(0);对于非零系数,负的 shift 会导致中止。
///|
test "trailing factors" {
debug_inspect(@internal.remove_factor10(-1200N, 3), content="(-12, 5)")
debug_inspect(
@internal.trim_trailing_decimal_zeros(1000N, 0, max_drop=2),
content="(10, 2, 2)",
)
debug_inspect(@internal.exact_divide_by_power_of_ten(1201N, 2), content="None")
}
整数商的舍入
round_positive_div
round_positive_div(n, d, negative, mode) 将商 舍入为一个整数量值。
pub fn round_positive_div(@bigint.BigInt, @bigint.BigInt, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt
要求 且 (否则中止)。negative 是量值为 的实数商的符号;结果为 ,其中 表示舍入到整数:
mode | 对 、 的结果 |
|---|---|
TowardZero | |
TowardPositive | |
TowardNegative | |
AwayFromZero | |
ToNearestEven |
结果是精确的(等于 )当且仅当 。
///|
test "rounding -5/2 and -7/2" {
let modes = [
@lf_arith.RoundingMode::ToNearestEven,
@lf_arith.RoundingMode::TowardZero,
@lf_arith.RoundingMode::TowardPositive,
@lf_arith.RoundingMode::TowardNegative,
@lf_arith.RoundingMode::AwayFromZero,
]
let five = modes.map(m => @internal.round_positive_div(5N, 2N, true, m).to_string())
let seven = modes.map(m => @internal.round_positive_div(7N, 2N, true, m).to_string())
inspect(five.join(" "), content="2 2 2 3 3")
inspect(seven.join(" "), content="4 3 3 4 4")
}
round_shift
round_shift(m, s, negative, mode) 即用移位计算的 round_positive_div(m, 2^s, negative, mode)。
pub fn round_shift(@bigint.BigInt, Int, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt
对于 ,它原样返回 (从不左移)。 应为非负数;这一点不会被检查。对于负的 ,商是算术移位的下取整 ,余数为非负,因此上表不再描述 的舍入:round_shift(-5N, 1, false, TowardZero) 为 ,而不是 。
十进制字符串
split_decimal_string, split_decimal_string_wide
split_decimal_string(text) 将一个有限十进制字面量拆分为符号、数字串和指数;split_decimal_string_wide 以 Int64 返回指数。
pub fn split_decimal_string(String) -> (Bool, String, Int)?
pub fn split_decimal_string_wide(String) -> (Bool, String, Int64)?
所接受的语法为
[+|-] digit* [. digit*] [(e|E) [+|-] digit+] with at least one mantissa digit
结果 满足 ,其中 是全部尾数数字组成的字符串(保留前导零), 是书写的指数减去小数部分的位数。在宽版本中,书写的指数在绝对值不超过 时是精确的,超出则饱和于此,这远在任何指数范围之外。当 不能放入 Int 时,split_decimal_string 返回 None。其他任何输入,包括空白、_、inf 和 nan,都得到 None。
///|
test "split decimal string" {
debug_inspect(
@internal.split_decimal_string("-12.50e3"),
content="Some((true, \"1250\", 1))",
)
debug_inspect(@internal.split_decimal_string(".5"), content="Some((false, \"5\", -1))")
debug_inspect(@internal.split_decimal_string("1e"), content="None")
debug_inspect(@internal.split_decimal_string("1e3000000000"), content="None")
debug_inspect(@internal.split_decimal_string_wide("1e3000000000"), content="Some((false, \"1\", 3000000000))")
}
二进有理数包络
CertifiedDyadic
CertifiedDyadic 是二进有理数 ,其中 为 numerator_,标度 = scale_ 非负。
pub struct CertifiedDyadic {
numerator_ : @bigint.BigInt
scale_ : Int
}
这些字段可读,但无法在包外以字面量方式构建该结构体;请用 new 或 from_int 构建值。
CertifiedDyadic::new, CertifiedDyadic::from_int, CertifiedDyadic::numerator, CertifiedDyadic::scale
new(n, s) 为 (若 则中止);from_int(k) 为 ;访问器返回各字段。
pub fn CertifiedDyadic::new(@bigint.BigInt, Int) -> Self
pub fn CertifiedDyadic::from_int(Int) -> Self
pub fn CertifiedDyadic::numerator(Self) -> @bigint.BigInt
pub fn CertifiedDyadic::scale(Self) -> Int
该表示未经规范化: 和 是该结构体的两个不同的值,但表示同一个数。
CertifiedDyadic::add, CertifiedDyadic::sub, CertifiedDyadic::mul, CertifiedDyadic::neg, CertifiedDyadic::compare
这些方法是二进有理数的精确算术与比较。
pub fn CertifiedDyadic::add(Self, Self) -> Self
pub fn CertifiedDyadic::sub(Self, Self) -> Self
pub fn CertifiedDyadic::mul(Self, Self) -> Self
pub fn CertifiedDyadic::neg(Self) -> Self
pub fn CertifiedDyadic::compare(Self, Self) -> Int
add 和 sub 对齐到较大的标度;mul 将标度相加;compare 比较的是数值(而非表示),因此 new(2N, 1).compare(from_int(1)) 为 0。
CertifiedDyadic::round_down, CertifiedDyadic::round_up
x.round_down(s) 和 x.round_up(s) 分别是标度为 的二进有理数中 的最大者和 的最小者: 与 。
pub fn CertifiedDyadic::round_down(Self, Int) -> Self
pub fn CertifiedDyadic::round_up(Self, Int) -> Self
若 则中止。当 不小于当前标度时,值被精确地重新表示(分子左移)。对于负数,两个方向也都是真正的下取整和上取整:在标度 下, 向下舍入为 ,向上舍入为 。
CertifiedInterval
CertifiedInterval[T] 是一个满足 lower <= upper 的有序对,用作包络。
pub struct CertifiedInterval[T] {
lower_ : T
upper_ : T
}
CertifiedInterval::new, CertifiedInterval::lower, CertifiedInterval::upper
new(lower, upper, compare) 用给定的比较函数检查顺序并构建该二元组;lower 和 upper 返回端点。
pub fn[T] CertifiedInterval::new(T, T, (T, T) -> Int) -> Result[Self[T], @arithmetic.ArithmeticError]
pub fn[T] CertifiedInterval::lower(Self[T]) -> T
pub fn[T] CertifiedInterval::upper(Self[T]) -> T
当 compare(lower, upper) > 0 时,new 返回一个针对运算 "interval" 的认证失败错误,其阶段为 EnclosurePropagation,原因为 InvalidEnclosure,目标精度和工作精度为 1,细化次数为 0。
certified_dyadic_fraction
certified_dyadic_fraction(n, d, s) 用两个标度为 的二进有理数包络 。
pub fn certified_dyadic_fraction(@bigint.BigInt, @bigint.BigInt, Int) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]
无论 的符号如何,结果都为 :它包含 ,宽度为 或 ,且当且仅当 时为单点。非正的 产生定义域错误。
certified_dyadic_div
certified_dyadic_div(a, b, s) 以标度 包络两个二进有理数的商 。
pub fn certified_dyadic_div(CertifiedDyadic, CertifiedDyadic, Int) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]
产生除以零错误。否则,结果是将 certified_dyadic_fraction 作用于写成正分母形式的 。
///|
test "one third at scale 8" {
let third = @internal.certified_dyadic_div(
@internal.CertifiedDyadic::from_int(1),
@internal.CertifiedDyadic::from_int(3),
8,
).unwrap()
inspect(third.lower().numerator(), content="85") // 85/256 <= 1/3
inspect(third.upper().numerator(), content="86") // 86/256 >= 1/3
let negative = @internal.certified_dyadic_fraction(-1N, 3N, 2).unwrap()
inspect(negative.lower().numerator(), content="-2") // -2/4 <= -1/3
inspect(negative.upper().numerator(), content="-1") // -1/4 >= -1/3
}
细化预算
CertifiedRefinementBudget
CertifiedRefinementBudget 跟踪 Ziv 式求值循环的工作精度和细化次数。
pub struct CertifiedRefinementBudget {
work_precision : Int
refinements_ : Int
limit_ : Int?
cap_ : Int
}
CertifiedRefinementBudget::new, CertifiedRefinementBudget::next, CertifiedRefinementBudget::available, CertifiedRefinementBudget::precision, CertifiedRefinementBudget::refinements
new(p, limit?) 以工作精度 、零次细化开始。limit 为 Some(n),即细化次数上限 (默认 Some(12)),或为 None,即没有次数限制。next() 将精度增加 ,并计入一次细化。只要已进行的细化次数少于 n,available() 就为真;对 None,则只要工作精度不超过起始精度对应的 certified_unbounded_work_cap,它就为真。
pub fn CertifiedRefinementBudget::new(Int, limit? : Int?) -> Self
pub fn CertifiedRefinementBudget::next(Self) -> Self
pub fn CertifiedRefinementBudget::available(Self) -> Bool
pub fn CertifiedRefinementBudget::precision(Self) -> Int
pub fn CertifiedRefinementBudget::refinements(Self) -> Int
next 不检查 available;循环必须自行检测 available()。
///|
test "budget schedule" {
let mut budget = @internal.CertifiedRefinementBudget::new(64, limit=Some(3))
let seen = []
while budget.available() {
seen.push(budget.precision().to_string())
budget = budget.next()
}
inspect(seen.join(" -> "), content="64 -> 96 -> 144")
inspect(budget.precision(), content="216")
inspect(budget.refinements(), content="3")
}
certified_refinement_continues, certified_unbounded_work_cap
certified_refinement_continues(limit, attempt, work, precision) 告诉手写的细化循环是否还可以再运行一步:Some(n) 允许 attempt < max(1, n),None 则在 work 不超过 certified_unbounded_work_cap(precision) 时允许。该上限取 8,000,000 与 precision 的 256 倍中较大者,至多为 1,000,000,000。
pub fn certified_refinement_continues(Int?, Int, Int, Int) -> Bool
pub fn certified_unbounded_work_cap(Int) -> Int
certified_failure
certified_failure(operation, stage, reason, target_precision, budget) 构建经认证运算放弃时返回的 ArithmeticError。
pub fn certified_failure(String, @arithmetic.CertificationStage, @arithmetic.CertificationFailureReason, Int, CertifiedRefinementBudget) -> @arithmetic.ArithmeticError
该错误的详情记录运算名、阶段、原因、目标精度,以及预算当前的工作精度和细化次数。
完整公共接口
此快照是该包生成的 pkg.generated.mbti。当正文与接口不一致时,以接口为准。
// Generated using `moon info`, DON'T EDIT IT
package "Luna-Flow/floating/internal"
import {
"Luna-Flow/arithmetic",
"moonbitlang/core/bigint",
}
// Values
pub fn abs_bigint(@bigint.BigInt) -> @bigint.BigInt
pub fn bigint_one() -> @bigint.BigInt
pub fn bigint_zero() -> @bigint.BigInt
pub fn certified_dyadic_div(CertifiedDyadic, CertifiedDyadic, Int32) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]
pub fn certified_dyadic_fraction(@bigint.BigInt, @bigint.BigInt, Int32) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]
pub fn certified_failure(String, @arithmetic.CertificationStage, @arithmetic.CertificationFailureReason, Int32, CertifiedRefinementBudget) -> @arithmetic.ArithmeticError
pub fn certified_refinement_continues(Int32?, Int32, Int32, Int32) -> Bool
pub fn certified_unbounded_work_cap(Int32) -> Int32
pub fn compare_abs(@bigint.BigInt, @bigint.BigInt) -> Int32
pub let decimal_exponent_limit : Int32
pub fn digits10(@bigint.BigInt) -> Int32
pub fn exact_divide_by_power_of_ten(@bigint.BigInt, Int32) -> @bigint.BigInt?
pub fn pow10(Int32) -> @bigint.BigInt
pub fn pow5(Int32) -> @bigint.BigInt
pub fn remove_factor10(@bigint.BigInt, Int32) -> (@bigint.BigInt, Int32)
pub fn round_positive_div(@bigint.BigInt, @bigint.BigInt, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt
pub fn round_shift(@bigint.BigInt, Int32, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt
pub fn split_decimal_string(String) -> (Bool, String, Int32)?
pub fn split_decimal_string_wide(String) -> (Bool, String, Int64)?
pub fn trim_trailing_decimal_zeros(@bigint.BigInt, Int32, max_drop? : Int32) -> (@bigint.BigInt, Int32, Int32)
// Errors
// Types and methods
pub struct CertifiedDyadic {
numerator_ : @bigint.BigInt
scale_ : Int32
}
pub fn CertifiedDyadic::add(Self, Self) -> Self
pub fn CertifiedDyadic::compare(Self, Self) -> Int32
pub fn CertifiedDyadic::from_int(Int32) -> Self
pub fn CertifiedDyadic::mul(Self, Self) -> Self
pub fn CertifiedDyadic::neg(Self) -> Self
pub fn CertifiedDyadic::new(@bigint.BigInt, Int32) -> Self
pub fn CertifiedDyadic::numerator(Self) -> @bigint.BigInt
pub fn CertifiedDyadic::round_down(Self, Int32) -> Self
pub fn CertifiedDyadic::round_up(Self, Int32) -> Self
pub fn CertifiedDyadic::scale(Self) -> Int32
pub fn CertifiedDyadic::sub(Self, Self) -> Self
pub struct CertifiedInterval[T] {
lower_ : T
upper_ : T
}
pub fn[T] CertifiedInterval::lower(Self[T]) -> T
pub fn[T] CertifiedInterval::new(T, T, (T, T) -> Int32) -> Result[Self[T], @arithmetic.ArithmeticError]
pub fn[T] CertifiedInterval::upper(Self[T]) -> T
pub struct CertifiedRefinementBudget {
work_precision : Int32
refinements_ : Int32
limit_ : Int32?
cap_ : Int32
}
pub fn CertifiedRefinementBudget::available(Self) -> Bool
pub fn CertifiedRefinementBudget::new(Int32, limit? : Int32?) -> Self
pub fn CertifiedRefinementBudget::next(Self) -> Self
pub fn CertifiedRefinementBudget::precision(Self) -> Int32
pub fn CertifiedRefinementBudget::refinements(Self) -> Int32
pub struct DecimalExponentBounds {
valid_ : Bool
etiny_ : Int32
etop_ : Int32
}
pub fn DecimalExponentBounds::etiny(Self) -> Int32
pub fn DecimalExponentBounds::etop(Self) -> Int32
pub fn DecimalExponentBounds::is_valid(Self) -> Bool
pub fn DecimalExponentBounds::new(Int32, Int32, Int32) -> Self
// Type aliases
// Traits