Slightly improve calculation of standardized moment

Also test more of the trivial cases.
This commit is contained in:
Vinzent Steinberg 2018-07-11 12:37:06 +02:00
parent 3e7a66b519
commit 34d33ef21a
2 changed files with 8 additions and 4 deletions

View File

@ -125,14 +125,16 @@ macro_rules! define_moments {
/// Estimate the `p`th standardized moment of the population.
#[inline]
pub fn standardized_moment(&self, p: usize) -> f64 {
let variance = self.central_moment(2);
assert_ne!(variance, 0.);
let n = f64::approx_from(self.n).unwrap();
match p {
0 => n,
1 => 0.,
2 => 1.,
_ => self.central_moment(p) / pow(variance.sqrt(), p),
_ => {
let variance = self.central_moment(2);
assert_ne!(variance, 0.);
let n = f64::approx_from(self.n).unwrap();
self.central_moment(p) / pow(variance.sqrt(), p)
},
}
}

View File

@ -14,6 +14,8 @@ use average::{Moments4, Merge};
fn trivial() {
let mut a = Moments4::new();
assert_eq!(a.len(), 0);
assert_eq!(a.central_moment(1), 0.0);
assert_eq!(a.standardized_moment(2), 1.0);
a.add(1.0);
assert_eq!(a.len(), 1);
assert_eq!(a.mean(), 1.0);