3个不稳定版本
0.8.0 | 2020年2月8日 |
---|---|
0.7.1 | 2020年2月8日 |
0.7.0 | 2020年2月6日 |
#1507 in 数学
21KB
419 行
val_unc
一个处理具有不确定性的数量的包。
ValUnc
类型代表一个具有平均值 val
和不确定性 unc
的数量。它设计用于与包装基本数字类型的新类型一起使用,例如 f64
。这允许类型定义不确定性的传播方式,最小化混淆。
traits 模块定义了一些必须实现以在 ValUnc
中实现相关类型的特质的特质的。例如,为了实现 Add
,必须使用所有的不确定性类型实现 UncAdd
。这些是可选的,并且只需要实现使用的特质。
在 unc
中提供了一个不确定性类型的示例实现。它使用标准的误差传播规则(见 此处),希望它适合您的用例。
功能
可以启用 serde
功能,以便与 serde
一起使用。一个 ValUnc<V, U>
被序列化为 (V, U)
或如果 unc
为零,根据 num-traits::Zero
,只是一个 V
。
示例
以下演示了如何创建不确定性类型以及实现使用 ValUnc
进行数学运算所需的特质(在这种情况下仅 Add
)。值得注意的是, UncAdd
的实现不同。然而,这两个不确定性可以在一个 ValUnc
中一起使用。
use val_unc::{ValUnc, UncAdd};
// This is a type for statistical uncertainties.
// The result of adding two `StatUnc`s is the square root of the sum of the squares.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
struct StatUnc(pub f64);
impl<T> UncAdd<T> for StatUnc {
fn unc_add(self, _self_val: T, other: Self, _other_val: T) -> Self {
Self(f64::sqrt(f64::powi(self.0, 2) + f64::powi(other.0, 2)))
}
}
// This is a type for systematic uncertainties.
// The result of adding two `SysUnc`s is the sum of the two.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default)]
struct SysUnc(pub f64);
impl<T> UncAdd<T> for SysUnc {
fn unc_add(self, _self_val: T, other: Self, _other_val: T) -> Self {
Self(self.0 + other.0)
}
}
// Create two values and add them together
let v1 = ValUnc::new(10.2, (StatUnc(4.0), SysUnc(1.25)));
let v2 = ValUnc::new(8.5, (StatUnc(3.0), SysUnc(1.25)));
// You can use destructuring to unpack the results
let ValUnc { val, unc: (stat, sys) } = v1 + v2;
assert!(f64::abs(val - 18.7) <= std::f64::EPSILON);
assert!(f64::abs(stat.0 - 5.0) <= std::f64::EPSILON);
assert!(f64::abs(sys.0 - 2.5) <= std::f64::EPSILON);
依赖关系
~95–325KB