def API

用途

def 是 floating 各包的共享词汇。它定义了符号分类 Sign、十值的 IEEE 类别 IeeeClass、四路比较结果 PartialOrder、本仓库中每种标量表示都实现的 trait Floating、基于该 trait 构建的四个泛型谓词,并重新导出 Luna-Flow/arithmetic 中的上下文、舍入、分类和错误类型,使调用者只需一次导入。它不包含任何算术运算。教程 展示了这些词汇的用法;设计页面 陈述了 trait 定律,并解释了为何 PartialOrder 不是全序。

导入

将该包添加到你的 moon.pkg 中,与你所用的表示放在一起:

import {
  "Luna-Flow/floating/def",
  "Luna-Flow/floating/binary",
}

本页示例都是完整的测试。它们以 @def. 调用该包,以 @binary.、@decimal.、@decimal_gda. 和 @interval. 调用各表示,并以 @lf_arith. 调用 Luna-Flow/arithmetic。

符号与比较结果

Sign

Sign 是 Floating::signum 返回的三路符号分类。

pub(all) enum Sign {
  Negative
  Zero
  Positive
} derive(Eq)

两种带符号零都返回 Zero,因此 Sign 不区分 −0-0 与 +0+0;当零的符号位很重要时,请使用具体的包(例如 Binary::is_negative_zero)。标量实现对每个 NaN 也返回 Zero(参见 Floating::signum)。Sign 也是 semantic 包中 SemanticScalar::Infinity 的载荷,以及 Binary::inf 等构造函数的参数。

///|
test "Sign values" {
  let s = @def.Floating::signum(@binary.Binary::from_int(-3))
  inspect(s == @def.Sign::Negative, content="true")
  let z = @def.Floating::signum(@binary.Binary::from_double(-0.0))
  inspect(z == @def.Sign::Zero, content="true")
}

IeeeClass

IeeeClass 是 IEEE 754-2019 第 5.7.2 条的十值 class。与 FpClass 不同,它区分两种 NaN、每个类别的符号,以及正规、次正规和零。

pub(all) enum IeeeClass {
  SignalingNaN
  QuietNaN
  NegativeInfinity
  NegativeNormal
  NegativeSubnormal
  NegativeZero
  PositiveZero
  PositiveSubnormal
  PositiveNormal
  PositiveInfinity
} derive(Eq)

Binary::class_of 和 Decimal::class_of 返回它。正规与次正规取决于格式的 emin⁡e_{\min},所以两者都接受确定它的上下文。

///|
test "IeeeClass of a binary32 value" {
  let ctx = @binary.BinaryInterchangeFormat::Binary32.context()
  let tiny = @binary.Binary::make(@binary.BinCoeff::one(), -127, 24)
  inspect(tiny.class_of(ctx) == @def.IeeeClass::PositiveSubnormal, content="true")
  inspect(tiny.neg().class_of(ctx) == @def.IeeeClass::NegativeSubnormal, content="true")
}

PartialOrder

PartialOrder 是 IEEE 754 比较的结果:两个浮点数据之间恰好成立 小于、等于、大于 和 无序 这四种互斥关系之一。

pub(all) enum PartialOrder {
  Less
  Equal
  Greater
  Unordered
} derive(Eq)

当且仅当至少一个操作数为 NaN 时 Unordered 成立;−0-0 和 +0+0 比较 Equal。该类型由 binary 中的 Binary::compare_quiet 和 Binary::compare_signaling 返回(各自附带该比较的标志)。它仅是一个值类型;def 本身不执行任何比较。为何是四种结果而非 Compare 实例,其推导见设计页面。

///|
test "PartialOrder from an IEEE comparison" {
  let one = @binary.Binary::from_int(1)
  let nan = @binary.Binary::nan()
  let (relation, flags) = one.compare_quiet(nan)
  inspect(relation == @def.PartialOrder::Unordered, content="true")
  inspect(flags.invalid_operation(), content="false")
  let (signaling, signaling_flags) = one.compare_signaling(nan)
  inspect(signaling == @def.PartialOrder::Unordered, content="true")
  inspect(signaling_flags.invalid_operation(), content="true")
  let zeros = @binary.Binary::from_double(-0.0).compare_quiet(
    @binary.Binary::zero(),
  )
  inspect(zeros.0 == @def.PartialOrder::Equal, content="true")
}

Floating trait

Floating

Floating 是本仓库中所有表示共享的观察与重设精度接口。

pub(open) trait Floating {
  fn classify(Self) -> @arithmetic.FpClass
  fn sign(Self) -> Sign
  fn precision(Self) -> Int
  fn with_precision(Self, Int) -> Self
  fn normalized(Self) -> Self
}

Floating 只由本库的标量类型实现:@binary.Binary、@decimal.Decimal 和 @decimal_gda.Decimal。@interval.Interval 不实现它(参见区间不是 Floating)。它不是扩展点:为本模块之外的类型实现它不受支持,也不在兼容性承诺之内,因为 trait 可能在次版本中增加方法。它被声明为 pub(open),只是因为这些实现位于本模块的其他包中(原因见设计页面)。自 MoonBit 0.10 迁移以来,trait 方法不再自动提升,因此泛型代码以限定形式 @def.Floating::classify(x) 调用它们;具体类型也提供同名的固有方法(x.classify())。每个实现应满足的定律列于设计页面。

Floating::classify

classify 返回值的类别:Finite、Infinity 或 NaN。

fn classify(Self) -> @arithmetic.FpClass

对标量类型,这是 IEEE 类别,其中信号 NaN 与安静 NaN 合并。它是全函数,从不中止。

Floating::signum

signum 返回值的符号分类。

fn sign(Self) -> Sign
实现NegativeZeroPositive
Binary,两种 Decimal值 <0< 0,包括 −∞-\infty±0\pm 0 及所有 NaN值 >0> 0,包括 +∞+\infty

Floating::precision

precision 返回值上存储的工作精度。

fn precision(Self) -> Int

对 Binary,它计算有效二进制位数;对两种 Decimal 类型,它计算有效十进制位数。每个构造函数都会将存储的精度限制为至少 11,因此结果总是至少为 11。

Floating::with_precision

with_precision(x, p) 返回以精度 q=max⁡(1,p)q = \max(1, p) 重新表示的 x。

fn with_precision(Self, Int) -> Self

对有限标量,值就近舍入(偶数优先,IEEE 754-2019 4.3.1)到其基数下的 qq 位有效数字。trait 方法没有舍入参数,因为它无法返回错误;各标量类型自己的 with_precision 接受舍入模式。不应用上下文的指数界限,也不报告标志(两者都需要时请使用具体包的 *_ctx API)。十进制类型没有其他指数限制。Binary 保留其实现范围:指数超出 [1−emax⁡,emax⁡][1 - e_{\max}, e_{\max}](其中 emax⁡=230−1e_{\max} = 2^{30} - 1;binary_value_e_max、binary_value_e_min)的结果会像 IEEE 754 中那样上溢为无穷或最大有限值,或者下溢。零保留其符号。无穷和 NaN 保留其类别、符号和载荷,只改变存储的精度。

Floating::normalized

normalized 返回值的规范代表。

fn normalized(Self) -> Self

对于 Binary,这是系数为奇数(或为零)的表示;对于两种 Decimal 类型,它去除系数末尾的零,因此 1.500 变为 1.5(同值类改变,值不变),-0.000 变为 -0。非有限标量原样返回。在标量类型上,normalized 保持值不变,并且是幂等的。

///|
fn[F : @def.Floating] describe(x : F) -> String {
  let class = match @def.Floating::classify(x) {
    Finite => "finite"
    Infinity => "infinite"
    NaN => "nan"
  }
  let sign = match @def.Floating::signum(x) {
    Negative => "-"
    Zero => "0"
    Positive => "+"
  }
  "\{class} \{sign} precision=\{@def.Floating::precision(x)}"
}

///|
test "Floating observations" {
  inspect(
    describe(@binary.Binary::from_double(-0.0)),
    content="finite 0 precision=53",
  )
  inspect(
    describe(@decimal.Decimal::from_string("-1.50").unwrap()),
    content="finite - precision=34",
  )
  inspect(
    describe(@decimal_gda.Decimal::from_string("-Inf").unwrap()),
    content="infinite - precision=34",
  )
}

///|
test "Floating re-precision and normalization" {
  let d = @decimal.Decimal::from_string("2.71828").unwrap()
  let cut = @def.Floating::with_precision(d, 3)
  inspect(cut.to_string(), content="2.72")
  let ten = @def.Floating::with_precision(
    @binary.Binary::from_int(10),
    2,
  )
  inspect(ten.to_string(), content="1p3")
  inspect(ten.precision(), content="2")
  let cohort = @decimal.Decimal::from_string("1.500").unwrap()
  inspect(@def.Floating::normalized(cohort).to_string(), content="1.5")
}

泛型谓词

is_finite, is_infinite, is_nan, is_zero

这些函数检测任意 Floating 值的类别。

pub fn[F : Floating] is_finite(F) -> Bool
pub fn[F : Floating] is_infinite(F) -> Bool
pub fn[F : Floating] is_nan(F) -> Bool
pub fn[F : Floating] is_zero(F) -> Bool
is_finite(x)  ⟺  classify(x)=Finite,is_infinite(x)  ⟺  classify(x)=Infinity,is_nan(x)  ⟺  classify(x)=NaN,is_zero(x)  ⟺  classify(x)=Finite∧sign(x)=Zero.\begin{aligned} \texttt{is\_finite}(x) &\iff \texttt{classify}(x) = \texttt{Finite},\\ \texttt{is\_infinite}(x) &\iff \texttt{classify}(x) = \texttt{Infinity},\\ \texttt{is\_nan}(x) &\iff \texttt{classify}(x) = \texttt{NaN},\\ \texttt{is\_zero}(x) &\iff \texttt{classify}(x) = \texttt{Finite} \wedge \texttt{sign}(x) = \texttt{Zero}. \end{aligned}

对每个值,前三者恰有一个为真。is_zero 对两种带符号零都为真,对 NaN 为假。

///|
test "generic predicates" {
  inspect(@def.is_zero(@binary.Binary::from_double(-0.0)), content="true")
  inspect(
    @def.is_finite(@decimal.Decimal::from_string("NaN").unwrap()),
    content="false",
  )
}

重新导出的类型

def 以 pub using 重新导出这些类型,因此 @def.RoundingMode 与 @lf_arith.RoundingMode 指同一类型,无需任何转换。它们的定义和完整语义由 Luna-Flow/arithmetic 文档说明。

ArithmeticContext

ArithmeticContext 是传递给 Luna-Flow/arithmetic 上下文 trait 的精度、舍入方向及可选指数界限。

pub using @arithmetic {type ArithmeticContext}

BinaryContext 和 DecimalContext 由各自的 from_arithmetic_context 构造函数从它构建。

ArithmeticError, ArithmeticErrorKind

ArithmeticError 是所有返回 Result 的 API(*_checked、try_*)以及各 checked 包装包的结构化错误;ArithmeticErrorKind 是其种类。

pub using @arithmetic {type ArithmeticError}
pub using @arithmetic {type ArithmeticErrorKind}

种类有 DivisionByZero、ParseError、DomainError、FormatError、UnsupportedOperation、UnorderedComparison 和 CertificationFailure(detail);ArithmeticError 为每个种类提供一个 is_* 谓词,并提供 message。

CertificationFailureDetail, CertificationFailureReason, CertificationStage

这些类型是种类为 CertificationFailure 的 ArithmeticError 的载荷:表示某个初等函数的正确舍入结果未能在其细化预算内完成认证。

pub using @arithmetic {type CertificationFailureDetail}
pub using @arithmetic {type CertificationFailureReason}
pub using @arithmetic {type CertificationStage}

详情记录运算、阶段和原因、目标精度,以及最终的工作精度和细化次数(参见内部 API 中的 certified_failure)。

FpClass

FpClass 是 Floating::classify 的结果:Finite、Infinity 或 NaN。

pub using @arithmetic {type FpClass}

RoundingMode

RoundingMode 列出具体类型自身的 with_precision 方法及各具体构造函数接受的五种舍入方向(trait 方法 Floating::with_precision 不接受):ToNearestEven、TowardZero、TowardPositive、TowardNegative 和 AwayFromZero。

pub using @arithmetic {type RoundingMode}

BigInt

BigInt 是 moonbitlang/core/bigint 的任意精度整数,用于表示系数和精确值。

pub using @bigint {type BigInt}
///|
test "aliases name the arithmetic types" {
  let ctx : @def.ArithmeticContext = @lf_arith.ArithmeticContext::new(10)
  inspect(ctx.precision, content="10")
  let mode : @def.RoundingMode = ToNearestEven
  inspect(mode == @lf_arith.RoundingMode::ToNearestEven, content="true")
}

trait 实现

Sign::equal, Sign::not_equal, PartialOrder::equal, PartialOrder::not_equal

这些方法是派生的 Eq 实例,经显式提升以使 a.equal(b) 仍然可用;请优先使用 == 和 !=。

pub fn Sign::equal(Self, Self) -> Bool
pub fn Sign::not_equal(Self, Self) -> Bool
pub fn PartialOrder::equal(Self, Self) -> Bool
pub fn PartialOrder::not_equal(Self, Self) -> Bool

完整公共接口

以下快照是该包完整的生成接口。

// Generated using `moon info`, DON'T EDIT IT
package "Luna-Flow/floating/def"

import {
  "Luna-Flow/arithmetic",
  "moonbitlang/core/bigint",
}

// Values
pub fn[F : Floating] is_finite(F) -> Bool

pub fn[F : Floating] is_infinite(F) -> Bool

pub fn[F : Floating] is_nan(F) -> Bool

pub fn[F : Floating] is_zero(F) -> Bool

// Errors

// Types and methods
#derive(Eq)
pub(all) enum IeeeClass {
  SignalingNaN
  QuietNaN
  NegativeInfinity
  NegativeNormal
  NegativeSubnormal
  NegativeZero
  PositiveZero
  PositiveSubnormal
  PositiveNormal
  PositiveInfinity
}

#derive(Eq)
pub(all) enum PartialOrder {
  Less
  Equal
  Greater
  Unordered
}
pub fn PartialOrder::equal(Self, Self) -> Bool
pub fn PartialOrder::not_equal(Self, Self) -> Bool

#derive(Eq)
pub(all) enum Sign {
  Negative
  Zero
  Positive
}
pub fn Sign::equal(Self, Self) -> Bool
pub fn Sign::not_equal(Self, Self) -> Bool

// Type aliases
pub using @arithmetic {type ArithmeticContext}

pub using @arithmetic {type ArithmeticError}

pub using @arithmetic {type ArithmeticErrorKind}

pub using @bigint {type BigInt}

pub using @arithmetic {type CertificationFailureDetail}

pub using @arithmetic {type CertificationFailureReason}

pub using @arithmetic {type CertificationStage}

pub using @arithmetic {type FpClass}

pub using @arithmetic {type RoundingMode}

// Traits
pub(open) trait Floating {
  fn classify(Self) -> @arithmetic.FpClass
  fn signum(Self) -> Sign
  fn precision(Self) -> Int32
  fn with_precision(Self, Int32) -> Self
  fn normalized(Self) -> Self
}