internal API
目的
internal は数値コアのための厳密な整数・有理数のヘルパーを収めています。内容は、2・5・10 のべき、桁数の計算、末尾の因数の除去、明示的な丸めモードによる整数除算、10 進文字列の分割器、既約有理数、2 進有理数(dyadic)による包含区間、および認証付き初等関数の精緻化予算です。これは内部パッケージであり、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.、Luna-Flow/arithmetic を @lf_arith. として呼び出します。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) は の 10 進桁数で、digits10(0) == 1 です。
pub fn digits10(@bigint.BigInt) -> Int
に対しては を満たす唯一の を返します。ビット長に基づく推定値から出発し、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)
値 と符号は保たれ、新しい係数は 10 で割り切れません。ゼロに対しては を返します。
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)
、 を満たし、 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) は ではなく です。
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
結果 は を満たします。ここで は仮数部のすべての数字からなる文字列(先頭のゼロも保持)であり、 は記述された指数から小数部の桁数を引いたものです。ワイド版では、記述された指数は絶対値 まで正確で、そこで飽和しますが、これはどの指数範囲よりもはるかに外側です。 が 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 進有理数 です。ここで は 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
これらのメソッドは 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) は、スケール を持つ の最大の 2 進有理数と の最小の 2 進有理数、すなわち と です。
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) は をスケール の 2 つの 2 進有理数で挟みます。
pub fn certified_dyadic_fraction(@bigint.BigInt, @bigint.BigInt, Int) -> Result[CertifiedInterval[CertifiedDyadic], @arithmetic.ArithmeticError]
の符号によらず、結果は です。これは を含み、幅は または であり、点区間になるのはちょうど のときです。正でない は定義域エラーになります。
certified_dyadic_div
certified_dyadic_div(a, b, s) は 2 つの 2 進有理数の商 をスケール で挟みます。
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?) は作業精度 、精緻化 0 回で始まります。limit は Some(n)(精緻化回数の上限 、既定は Some(12))または None(回数の上限なし)です。next() は精度を だけ増やし、精緻化を 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