Skip to content

Commit

Permalink
fix: variance implementation for slices
Browse files Browse the repository at this point in the history
bug introduced in a3f78fe
  • Loading branch information
YeungOnion committed Oct 24, 2024
1 parent a3f78fe commit c8ed456
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/statistics/slice_statistics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -381,18 +381,29 @@ impl<D: AsMut<[f64]> + AsRef<[f64]>> StandardizedMoment<f64> for Data<D> {
// TODO: rewrite iterator statistics and rely on them instead
let mut iter = self.0.as_ref().iter().enumerate();

let mut sum = *iter.next()?.1;
let mut variance = 0.0;
// init single sample (mean=sample and M_2=0)
let mut n: f64 = 1.;
let mut mu = *iter.next()?.1;
let mut m2 = 0.0;

for (i, &x) in iter {
if x.is_nan() {
// fail early
return Some(f64::NAN);
}
let diff = (i + 1) as f64 * x - sum;
sum += x;
variance += diff * diff / (i * (i + 1)) as f64
n = (i + 1) as f64;
let delta = x - mu;
mu += delta / n;
m2 += delta * (x - mu);
}

if n == 1. {
// no sample variance for a single sample
None

Check warning on line 402 in src/statistics/slice_statistics.rs

View check run for this annotation

Codecov / codecov/patch

src/statistics/slice_statistics.rs#L402

Added line #L402 was not covered by tests
} else {
// normalize by bessel
Some(m2 / (n - 1.))
}
Some(variance / (self.0.as_ref().len() - 1) as f64)
}

fn skewness(&self) -> Self::Skew {
Expand Down

0 comments on commit c8ed456

Please sign in to comment.