internal API

目的

internal は数値コアのための厳密な整数・有理数のヘルパーを収めています。内容は、2・5・10 のべき、桁数の計算、末尾の因数の除去、明示的な丸めモードによる整数除算、10 進文字列の分割器、既約有理数、2 進有理数(dyadic)による包含区間、および認証付き初等関数の精緻化予算です。これは内部パッケージであり、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.、Luna-Flow/arithmetic を @lf_arith. として呼び出します。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| の 10 進桁数で、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 のべきとの比較で補正します(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 をすべて取り除き、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?) は末尾の 10 進のゼロを最大 max_drop 個まで取り除きます。

pub fn trim_trailing_decimal_zeros(@bigint.BigInt, Int, max_drop? : Int) -> (@bigint.BigInt, Int, Int)

c=c′⋅10kc = c' \cdot 10^{k}、e′=e+ke' = e + k を満たし、k≤k \le max_drop の制約のもとで kk が最大となる (c′,e′,k)(c', e', k) を返します。負の 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 は整数への丸めを表します。

moden=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) は −2-2 ではなく −3-3 です。

10 進文字列

split_decimal_string, split_decimal_string_wide

split_decimal_string(text) は有限の 10 進リテラルを符号、数字列、指数に分割します。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))")
}

2 進有理数による包含区間

CertifiedDyadic

CertifiedDyadic は 2 進有理数 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

これらのメソッドは 2 進有理数の厳密な算術と比較です。

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 の最大の 2 進有理数と ≥x\ge x の最小の 2 進有理数、すなわち ⌊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) は n/dn/d をスケール ss の 2 つの 2 進有理数で挟みます。

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) は 2 つの 2 進有理数の商 a/ba/b をスケール ss で挟みます。

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

b=0b = 0 はゼロ除算エラーになります。それ以外の場合、結果は a/ba/b を正の分母で書いたものに 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?) は作業精度 max⁡(1,p)\max(1, p)、精緻化 0 回で始まります。limit は Some(n)(精緻化回数の上限 max⁡(1,n)\max(1, n)、既定は Some(12))または None(回数の上限なし)です。next() は精度を max⁡(32,⌊p/2⌋)\max(32, \lfloor p/2 \rfloor) だけ増やし、精緻化を 1 回数えます。available() は、行った精緻化が n 回未満の間は真で、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