elementary API
elementary 包是 Dual[T] 所实现的 arithmetic 解析 trait 的门面包。它重新导出 Dual、Sqrt、SqrtChecked、Exponential、Logarithmic、Trigonometric 和 Constants。当你针对这些 trait 编写泛型代码并希望对其求导时,就导入它。求导规则列在 dual API 中。
导入
import {
"Luna-Flow/autodiff/elementary",
}
重新导出的类型
Dual
对偶数类型。
pub using @dual {type Dual}
解析 trait
| Trait | 方法 | Dual[T] 上的切向分量 |
|---|---|---|
Sqrt | sqrt | |
SqrtChecked | sqrt_checked | ,带检查 |
Exponential | exp, exp2 | , |
Logarithmic | ln, log2, log10 | , , |
Trigonometric | sin, cos, tan | , , |
Constants | pi, tau, e |
Sqrt
不带检查的平方根。
pub using @arithmetic {trait Sqrt}
SqrtChecked
返回 Result[Self, ArithmeticError] 的平方根;见 checked API。
pub using @arithmetic {trait SqrtChecked}
Exponential
exp 与 exp2。Dual[T] 实例要求 T : Exponential + Logarithmic + IntegralHomomorphism + Mul,因为 exp2 用到了 。
pub using @arithmetic {trait Exponential}
Logarithmic
ln、log2 与 log10。Dual[T] 实例要求 T : Logarithmic + IntegralHomomorphism + Mul + Div。
pub using @arithmetic {trait Logarithmic}
Trigonometric
sin、cos 与 tan。Dual[T] 实例要求 T : Trigonometric + Mul + Neg + Div。
pub using @arithmetic {trait Trigonometric}
Constants
、 与 ;在 Dual[T] 上它们是切向分量为零的常数。
pub using @arithmetic {trait Constants}
fn[T : @elementary.Trigonometric + @elementary.Exponential + Mul] damped(x : T) -> T {
@elementary.Exponential::exp(x) * @elementary.Trigonometric::sin(x)
}
test "analytic traits on dual numbers" {
let y = damped(@elementary.Dual::variable(0.0))
assert_eq(y.value(), 0.0)
assert_eq(y.tangent(), 1.0) // e^0 (sin 0 + cos 0)
let tau : @elementary.Dual[Double] = @elementary.Constants::tau()
assert_eq(tau.tangent(), 0.0)
}