arithmetic API
目的
Luna-Flow/linear-algebra/arithmetic はリポジトリのスカラー演算層です。線形代数コードが使うスカラー型と trait を Luna-Flow/luna-generic と Luna-Flow/arithmetic から再公開し、五つの小さな演算 trait Abs、ApproxEq、CheckedDiv、CheckedSqrt、CheckedCompare を追加します。演算 trait はその演算が利用できることを表すだけで、代数法則は主張しません。
ソース: src/arithmetic/operation_traits.mbt、src/arithmetic/alias.mbt。考え方は arithmetic の設計 にあります。
インポート
moon.pkg で、このパッケージと、コンテキスト型とエラー型を提供する上流の Luna-Flow/arithmetic をインポートします。
///|
import {
"Luna-Flow/linear-algebra/arithmetic" @la_arithmetic,
"Luna-Flow/arithmetic" @lf_arith,
}
このページの例では、using 宣言を使わず、すべての名前に @la_arithmetic. のようなパッケージ接頭辞を付けて書きます。このマニュアルの全ページは一つのテストパッケージにまとめてコンパイルされるため、ページごとの宣言が衝突してしまうからです。
再公開される名前
このパッケージは上流の名前を pub using で再エクスポートします。そのため @la_arithmetic.Sqrt と @lf_arith.Sqrt は同じ trait を指し、上流の trait を実装したスカラー型は再エクスポートされた trait も満たします。完全な振る舞いは上流のドキュメント luna-generic と arithmetic にあります。
Zero, One, Inverse, Conjugate
これらは luna-generic のスカラー演算 trait、すなわち加法と乗法の単位元、乗法の逆元、共役を再エクスポートします。
pub using @luna-generic {trait Zero}
pub using @luna-generic {trait One}
pub using @luna-generic {trait Inverse}
pub using @luna-generic {trait Conjugate}
| 名前 | メソッド | 意味 |
|---|---|---|
Zero | zero() | 加法単位元 |
One | one() | 乗法単位元 |
Inverse | inv(x) | 。Float と Double のインスタンスは で中断する |
Conjugate | conjugate(x) | 。組み込みの実数型にはインスタンスがない |
これら自体は法則を述べません。意味を与えるのは luna-generic の構造 trait(Ring、Field など)です。
Sqrt, Cbrt, Power, Exponential, Logarithmic, Constants
これらは Luna-Flow/arithmetic の検査なしの解析的演算を再エクスポートします。
pub using @Luna-Flow/arithmetic {trait Sqrt}
pub using @Luna-Flow/arithmetic {trait Cbrt}
pub using @Luna-Flow/arithmetic {trait Power}
pub using @Luna-Flow/arithmetic {trait Exponential}
pub using @Luna-Flow/arithmetic {trait Logarithmic}
pub using @Luna-Flow/arithmetic {trait Constants}
| 名前 | メソッド | 意味 |
|---|---|---|
Sqrt | sqrt(x) | 。 では IEEE の NaN |
Cbrt | cbrt(x) | |
Power | pow(x, y) | |
Exponential | exp(x), exp2(x) | , |
Logarithmic | ln(x), log2(x), log10(x) | 対数 |
Constants | pi(), tau(), e() | , , |
このリポジトリが使うのは Sqrt です。mutable の cholesky_decomposition、eigen、frobenius_norm、std_dev がこれを必要とします。
SqrtChecked, DivChecked, CompareChecked
これらは Luna-Flow/arithmetic の検査付き演算を再エクスポートします。これらは IEEE の特殊値の代わりに Result を返します。
pub using @Luna-Flow/arithmetic {trait SqrtChecked}
pub using @Luna-Flow/arithmetic {trait DivChecked}
pub using @Luna-Flow/arithmetic {trait CompareChecked}
| 名前 | メソッド |
|---|---|
SqrtChecked | sqrt_checked(x, ctx) -> Result[Self, ArithmeticError] |
DivChecked | div_checked(x, y, ctx) -> Result[Self, ArithmeticError] |
CompareChecked | compare_checked(x, y) -> Result[Int, ArithmeticError] |
後述するローカルな trait CheckedSqrt、CheckedDiv、CheckedCompare は、Float と Double についてこれらに処理を委ねます。
ArithmeticContext, ArithmeticError, ArithmeticErrorKind, FpClass, RoundingMode
これらは検査付き演算が受け取り、返す型を再エクスポートします。
pub using @Luna-Flow/arithmetic {type ArithmeticContext}
pub using @Luna-Flow/arithmetic {type ArithmeticError}
pub using @Luna-Flow/arithmetic {type ArithmeticErrorKind}
pub using @Luna-Flow/arithmetic {type FpClass}
pub using @Luna-Flow/arithmetic {type RoundingMode}
| 名前 | 意味 |
|---|---|
ArithmeticContext | 精度、丸め、および省略可能な指数範囲(e_min、e_max、clamp)の設定。ArithmeticContext::new(precision) で作る |
ArithmeticError | フィールド kind と message を持つ構造化されたスカラーのエラー |
ArithmeticErrorKind | DivisionByZero、DomainError、UnorderedComparison、ParseError、FormatError、UnsupportedOperation、および証明付きバックエンド向けの CertificationFailure(detail)(Float と Double では生じない)。マッチするときはフォールバックの分岐を残すこと |
FpClass | Finite, Infinity, NaN |
RoundingMode | ToNearestEven, TowardZero, TowardPositive, TowardNegative, AwayFromZero |
///|
fn[T : @la_arithmetic.Zero + @la_arithmetic.Sqrt + Add + Mul] arith_api_hypot(
x : T,
y : T,
) -> T {
@la_arithmetic.Sqrt::sqrt(@la_arithmetic.Zero::zero() + x * x + y * y)
}
///|
test "re-exported traits are the upstream ones" {
inspect(arith_api_hypot(3.0, 4.0), content="5")
let ctx = @lf_arith.ArithmeticContext::new(53)
inspect(
@la_arithmetic.SqrtChecked::sqrt_checked(-1.0, ctx) is Err(_),
content="true",
)
}
絶対値
Abs
Abs は絶対値を持つスカラー型を表します。
pub(open) trait Abs {
fn abs(Self) -> Self
}
pub impl Abs for Int
pub impl Abs for Float
pub impl Abs for Double
Abs::abs
Abs::abs は を返します。
fn Abs::abs(Self) -> Self
実装は luna-generic の Num::abs に委譲します。Int では、2 の補数演算と同様に は に折り返されます。
///|
fn[T : @la_arithmetic.Abs] arith_api_magnitude(x : T) -> T {
@la_arithmetic.Abs::abs(x)
}
///|
test "Abs on integers and doubles" {
inspect(arith_api_magnitude(-3), content="3")
inspect(arith_api_magnitude(-2.5), content="2.5")
}
近似的な等しさ
ApproxEq
ApproxEq は近似比較を持つスカラー型を表します。
pub(open) trait ApproxEq {
fn approx_eq(Self, Self) -> Bool
}
pub impl ApproxEq for Int
pub impl ApproxEq for Float
pub impl ApproxEq for Double
ApproxEq::approx_eq
ApproxEq::approx_eq は、二つの値が固定の絶対許容誤差の範囲内にあるかどうかを返します。
fn ApproxEq::approx_eq(Self, Self) -> Bool
| 型 | 規則 |
|---|---|
Int | |
Float | |
Double |
許容誤差は絶対的なので、大きな値には厳しすぎ、小さな値には緩すぎます。また、この関係は推移的ではありません。オペランドのいずれかが NaN のとき、および無限大をそれ自身と比べたとき( は NaN)には false を返します。その帰結は 設計ページ を参照してください。
///|
test "ApproxEq uses an absolute tolerance" {
inspect(
@la_arithmetic.ApproxEq::approx_eq(1.0, 1.0 + 1.0e-13),
content="true",
)
inspect(
@la_arithmetic.ApproxEq::approx_eq(1.0e20, 1.0e20 + 1.0e5),
content="false",
)
inspect(@la_arithmetic.ApproxEq::approx_eq(3, 3), content="true")
}
検査付き演算
検査付き trait は NaN や無限大の代わりに Result[_, ArithmeticError] を返します。Float と Double の実装は上流の DivChecked、SqrtChecked、CompareChecked trait に委譲します。インターフェースを統一するために ArithmeticContext を受け取りますが、ハードウェアの二進浮動小数点は精度が固定なので無視します。
CheckedDiv
CheckedDiv は、不正なオペランドを報告する除算を持つスカラー型を表します。
pub(open) trait CheckedDiv {
fn checked_div(Self, Self, @Luna-Flow/arithmetic.ArithmeticContext) -> Result[Self, @Luna-Flow/arithmetic.ArithmeticError]
}
pub impl CheckedDiv for Float
pub impl CheckedDiv for Double
CheckedDiv::checked_div
CheckedDiv::checked_div(x, y, ctx) は Ok(x / y) またはエラーを返します。
fn CheckedDiv::checked_div(Self, Self, ArithmeticContext) -> Result[Self, ArithmeticError]
| オペランド | 結果 |
|---|---|
Err、種類 DomainError | |
Err、種類 DomainError | |
| 、( や NaN の場合も含む) | Err、種類 DivisionByZero |
| それ以外 | Ok(x / y)、最近接丸め。NaN のオペランドでは Ok(NaN) |
CheckedSqrt
CheckedSqrt は、定義域エラーを報告する平方根を持つスカラー型を表します。
pub(open) trait CheckedSqrt {
fn checked_sqrt(Self, @Luna-Flow/arithmetic.ArithmeticContext) -> Result[Self, @Luna-Flow/arithmetic.ArithmeticError]
}
pub impl CheckedSqrt for Float
pub impl CheckedSqrt for Double
CheckedSqrt::checked_sqrt
CheckedSqrt::checked_sqrt(x, ctx) は なら Ok(√x) を、 なら種類 DomainError のエラーを返します。
fn CheckedSqrt::checked_sqrt(Self, ArithmeticContext) -> Result[Self, ArithmeticError]
NaN の引数は Ok(NaN) としてそのまま通されます。
CheckedCompare
CheckedCompare は、順序付けできないオペランドを報告する三方向比較を持つスカラー型を表します。
pub(open) trait CheckedCompare {
fn checked_compare(Self, Self) -> Result[Int, @Luna-Flow/arithmetic.ArithmeticError]
}
pub impl CheckedCompare for Float
pub impl CheckedCompare for Double
CheckedCompare::checked_compare
CheckedCompare::checked_compare(x, y) は 、、 に対してそれぞれ Ok(-1)、Ok(0)、Ok(1) を返し、どちらかのオペランドが NaN なら種類 UnorderedComparison のエラーを返します。
fn CheckedCompare::checked_compare(Self, Self) -> Result[Int, ArithmeticError]
三つの検査付き trait をまとめて使う例:
///|
test "checked scalar operations" {
let ctx = @lf_arith.ArithmeticContext::new(53)
inspect(
@la_arithmetic.CheckedDiv::checked_div(6.0, 2.0, ctx).unwrap(),
content="3",
)
match @la_arithmetic.CheckedDiv::checked_div(1.0, 0.0, ctx) {
Err(e) => inspect(e.is_division_by_zero(), content="true")
Ok(_) => fail("1 / 0 must fail")
}
match @la_arithmetic.CheckedSqrt::checked_sqrt(-4.0, ctx) {
Err(e) => inspect(e.is_domain_error(), content="true")
Ok(_) => fail("sqrt(-4) must fail")
}
inspect(
@la_arithmetic.CheckedCompare::checked_compare(2.0, 3.0).unwrap(),
content="-1",
)
let nan = 0.0 / 0.0
inspect(
@la_arithmetic.CheckedCompare::checked_compare(nan, 1.0) is Err(_),
content="true",
)
}
trait が使われる場所
具体的な行列パッケージは、スカラーの制約を luna-generic(Zero、AddMonoid、Semiring、Field、Num)と Sqrt から取ります。@mutable の数値ルーチンはこの再公開を通じて Sqrt を使い、さらに独自の Tolerance trait を使います(mutable API を参照)。ローカルの trait Abs、ApproxEq と検査付き trait は下流のアルゴリズムのための部品であり、このリポジトリの行列メソッドでこれらを要求するものはありません。