Ensure math::variance() function does not divide by zero

This commit is contained in:
Tobie Morgan Hitchcock 2022-11-23 09:45:01 +00:00
parent f0745386cf
commit 37871ceb81

View file

@ -9,10 +9,15 @@ pub trait Variance {
impl Variance for Vec<Number> { impl Variance for Vec<Number> {
fn variance(self, sample: bool) -> Number { fn variance(self, sample: bool) -> Number {
let mean = self.mean(); match self.len() {
let len = Number::from(self.len() - sample as usize); 0 => Number::NAN,
let out = self.iter().map(|x| (x - &mean) * (x - &mean)).sum::<Number>() / len; 1 => Number::from(0),
len => {
out let mean = self.mean();
let len = Number::from(len - sample as usize);
let out = self.iter().map(|x| (x - &mean) * (x - &mean)).sum::<Number>() / len;
out
}
}
} }
} }