def API

目的

def は floating 各パッケージの共有語彙です。符号の分類 Sign、10 値の IEEE クラス IeeeClass、4 通りの比較結果 PartialOrder、このリポジトリのすべてのスカラー表現が実装するトレイト Floating、そのトレイトに基づく 4 つの汎用述語を定義し、Luna-Flow/arithmetic の文脈、丸め、分類、エラーの型を再エクスポートして、呼び出し側が 1 回のインポートで済むようにします。算術演算は含みません。チュートリアル は語彙の使い方を示し、設計ページ はトレイトの法則を述べ、PartialOrder が全順序でない理由を説明します。

インポート

使用する表現と並べて、moon.pkg にパッケージを追加します。

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

このページの例は完全なテストです。パッケージを @def.、各表現を @binary.、@decimal.、@decimal_gda.、@interval.、Luna-Flow/arithmetic を @lf_arith. として呼び出します。

符号と比較結果

Sign

Sign は Floating::signum が返す 3 通りの符号分類です。

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 条の 10 値の class です。FpClass と違い、2 種類の 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 比較の結果です。2 つの浮動小数点データの間には、互いに排他的な 4 つの関係 less、equal、greater、unordered のうちちょうど 1 つが成り立ちます。

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

Unordered が成り立つのは、少なくとも一方のオペランドが NaN であるときに限ります。−0-0 と +0+0 は Equal と比較されます。この型は binary の Binary::compare_quiet と Binary::compare_signaling が返します(それぞれ比較のフラグと対になっています)。これは値型にすぎず、def 自身は比較を行いません。Compare インスタンスではなく 4 通りの結果にした理由は設計ページで導いています。

///|
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 トレイト

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 ではないを参照)。拡張点ではありません。このモジュール外の型に実装することはサポートされず、互換性の約束の対象にもなりません。マイナーリリースでトレイトにメソッドを追加することがあるためです。pub(open) として宣言しているのは、実装がこのモジュールの別のパッケージにあるからにすぎません(理由は設計ページ)。MoonBit 0.10 への移行以降、トレイトのメソッドは自動では昇格されないため、汎用コードは修飾形 @def.Floating::classify(x) で呼びます。具体型には同名の固有メソッド(x.classify())もあります。すべての実装が満たすべき法則は設計ページにあります。

Floating::classify

classify は値のクラス Finite、Infinity、NaN のいずれかを返します。

fn classify(Self) -> @arithmetic.FpClass

スカラー型では、シグナル NaN と静かな NaN を統合した IEEE クラスです。全域関数で、中止することはありません。

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 型では有効 10 進桁数を数えます。すべてのコンストラクタは保存される精度を 11 以上に制限するため、結果は常に 11 以上です。

Floating::with_precision

with_precision(x, p) は x を精度 q=max⁡(1,p)q = \max(1, p) で表し直したものを返します。

fn with_precision(Self, Int) -> Self

有限のスカラーでは、値はその基数で qq 桁の有効数字に最近接偶数丸め(IEEE 754-2019 4.3.1)で丸められます。trait メソッドはエラーを返せないため丸めパラメータを持たず、各スカラー型の with_precision が丸めモードを受け取ります。コンテキストの指数の上下限は適用されず、フラグも報告されません(どちらも必要な場合は具体的なパッケージの *_ctx API を使ってください)。10 進型にはそれ以外の指数の制限はありません。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}

前の 3 つは、どの値に対してもちょうど 1 つが真です。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 のコンテキスト付きトレイトに渡される精度、丸め方向、および省略可能な指数の上下限です。

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 は種類ごとに 1 つの 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 メソッドと具体的なコンストラクタが受け付ける 5 つの丸め方向を列挙します(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")
}

トレイト実装

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
}