internal API

用途

internal 包含供各数值核心使用的精确整数与有理数辅助函数:2、5 和 10 的幂,数字位数计数,去除尾部因子,带显式舍入模式的整数除法,十进制字符串拆分器,最简有理数,二进有理数包络,以及经认证初等函数的细化预算。它是一个内部包:无法从 Luna-Flow/floating 之外导入,其接口可能在不另行通知的情况下变更。设计页面证明舍入与包络不变式;教程展示这些辅助函数如何组合使用。

并非每个核心都使用每个辅助函数。在当前分支上,库代码的使用情况如下:

包所用的辅助函数
decimal, decimal_gdasplit_decimal_string, round_positive_div, pow5, pow10, digits10, abs_bigint, bigint_zero, bigint_one, DecimalExponentBounds, decimal_exponent_limit, CertifiedRefinementBudget, certified_failure
binary, intervalCertifiedRefinementBudget, 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 为 emin⁡−p+1e_{\min} - p + 1,etop 为 emax⁡−p+1e_{\max} - p + 1。对于无效输入,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 常量 00 和 11。

pub fn bigint_zero() -> @bigint.BigInt
pub fn bigint_one() -> @bigint.BigInt

abs_bigint, compare_abs

abs_bigint(x) 为 ∣x∣|x|,compare_abs(a, b) 比较 ∣a∣|a| 与 ∣b∣|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

这些函数返回 5n5^n 和 10n10^n。

pub fn pow5(Int) -> @bigint.BigInt
pub fn pow10(Int) -> @bigint.BigInt

当 n<0n < 0 时它们会中止。pow5 和 pow10 读取一个进程级缓存,该缓存初始包含 n≤18n \le 18 的幂,并按需扩展到至多 n=4096n = 4096;更大的幂每次都重新计算,不做缓存。

digits10

digits10(x) 是 ∣x∣|x| 的十进制位数,且 digits10(0) == 1。

pub fn digits10(@bigint.BigInt) -> Int

对于 x≠0x \ne 0,它返回满足 10d−1≤∣x∣<10d10^{d-1} \le |x| < 10^{d} 的唯一 dd:先根据位长给出估计,再通过与 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)

值 coeff⋅10exp\mathit{coeff} \cdot 10^{\mathit{exp}} 和符号保持不变,且新的系数不能被 10 整除。零得到 (0,0)(0, 0)。

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)

它返回 (c′,e′,k)(c', e', k),满足 c=c′⋅10kc = c' \cdot 10^{k}、e′=e+ke' = e + k,且 kk 在 k≤k \le max_drop 的约束下取最大。负的 max_drop(默认 −1-1)将限制设为 digits10(c) - 1,该限制永远不会起作用,因为带有 kk 个尾随零的非零整数至少有 k+1k + 1 位数字;因此默认情况下会去除所有尾随零。零得到 (0,0,0)(0, 0, 0)。设置限制可让调用方在某个目标指数处停下,正如 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) 将商 n/dn/d 舍入为一个整数量值。

pub fn round_positive_div(@bigint.BigInt, @bigint.BigInt, Bool, @arithmetic.RoundingMode) -> @bigint.BigInt

要求 n≥0n \ge 0 且 d>0d > 0(否则中止)。negative 是量值为 n/dn/d 的实数商的符号;结果为 ∣∘mode((−1)negative n/d)∣|\circ_{\text{mode}}((-1)^{\text{negative}}\, n/d)|,其中 ∘\circ 表示舍入到整数:

mode对 n=qd+rn = qd + r、0≤r<d0 \le r < d 的结果
TowardZeroqq
TowardPositiveq+[r>0∧¬negative]q + [r > 0 \wedge \neg\text{negative}]
TowardNegativeq+[r>0∧negative]q + [r > 0 \wedge \text{negative}]
AwayFromZeroq+[r>0]q + [r > 0]
ToNearestEvenq+[2r>d∨(2r=d∧q odd)]q + [2r > d \vee (2r = d \wedge q \text{ odd})]

结果是精确的(等于 n/dn/d)当且仅当 r=0r = 0。

///|
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

对于 s≤0s \le 0,它原样返回 mm(从不左移)。mm 应为非负数;这一点不会被检查。对于负的 mm,商是算术移位的下取整 ⌊m/2s⌋\lfloor m / 2^{s} \rfloor,余数为非负,因此上表不再描述 ∣m∣|m| 的舍入:round_shift(-5N, 1, false, TowardZero) 为 −3-3,而不是 −2-2。

十进制字符串

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

结果 (neg,D,q)(\mathit{neg}, D, q) 满足 value=(−1)neg⋅D⋅10q\text{value} = (-1)^{\mathit{neg}} \cdot D \cdot 10^{q},其中 DD 是全部尾数数字组成的字符串(保留前导零),qq 是书写的指数减去小数部分的位数。在宽版本中,书写的指数在绝对值不超过 101810^{18} 时是精确的,超出则饱和于此,这远在任何指数范围之外。当 qq 不能放入 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 是二进有理数 n⋅2−sn \cdot 2^{-s},其中 nn 为 numerator_,标度 ss = scale_ 非负。

pub struct CertifiedDyadic {
  numerator_ : @bigint.BigInt
  scale_ : Int
}

这些字段可读,但无法在包外以字面量方式构建该结构体;请用 new 或 from_int 构建值。

CertifiedDyadic::new, CertifiedDyadic::from_int, CertifiedDyadic::numerator, CertifiedDyadic::scale

new(n, s) 为 n⋅2−sn \cdot 2^{-s}(若 s<0s < 0 则中止);from_int(k) 为 k⋅20k \cdot 2^{0};访问器返回各字段。

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

该表示未经规范化:2⋅2−12 \cdot 2^{-1} 和 1⋅201 \cdot 2^{0} 是该结构体的两个不同的值,但表示同一个数。

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) 分别是标度为 ss 的二进有理数中 ≤x\le x 的最大者和 ≥x\ge x 的最小者:⌊x⋅2s⌋⋅2−s\lfloor x \cdot 2^{s} \rfloor \cdot 2^{-s} 与 ⌈x⋅2s⌉⋅2−s\lceil x \cdot 2^{s} \rceil \cdot 2^{-s}。

pub fn CertifiedDyadic::round_down(Self, Int) -> Self
pub fn CertifiedDyadic::round_up(Self, Int) -> Self

若 s<0s < 0 则中止。当 ss 不小于当前标度时,值被精确地重新表示(分子左移)。对于负数,两个方向也都是真正的下取整和上取整:在标度 00 下,−5/4-5/4 向下舍入为 −2-2,向上舍入为 −1-1。

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) 用两个标度为 ss 的二进有理数包络 n/dn/d。

pub fn certified_dyadic_fraction(@bigint.BigInt, @bigint.BigInt, Int) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]

无论 nn 的符号如何,结果都为 [⌊n2s/d⌋2−s, ⌈n2s/d⌉2−s][\lfloor n 2^{s}/d \rfloor 2^{-s},\ \lceil n 2^{s}/d \rceil 2^{-s}]:它包含 n/dn/d,宽度为 00 或 2−s2^{-s},且当且仅当 d∣n2sd \mid n 2^{s} 时为单点。非正的 dd 产生定义域错误。

certified_dyadic_div

certified_dyadic_div(a, b, s) 以标度 ss 包络两个二进有理数的商 a/ba/b。

pub fn certified_dyadic_div(CertifiedDyadic, CertifiedDyadic, Int) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]

b=0b = 0 产生除以零错误。否则,结果是将 certified_dyadic_fraction 作用于写成正分母形式的 a/ba/b。

///|
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?) 以工作精度 max⁡(1,p)\max(1, p)、零次细化开始。limit 为 Some(n),即细化次数上限 max⁡(1,n)\max(1, n)(默认 Some(12)),或为 None,即没有次数限制。next() 将精度增加 max⁡(32,⌊p/2⌋)\max(32, \lfloor p/2 \rfloor),并计入一次细化。只要已进行的细化次数少于 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