From 032002dce964391e016bf880c894993246aec6eb Mon Sep 17 00:00:00 2001 From: Vasil Nikolov Date: Mon, 24 Apr 2023 01:22:57 +0300 Subject: [PATCH] initial, unoptimized algoritm --- src/base/statistics.rs | 27 +++++++++++++++++++++------ src/base/variance_test.rs | 2 +- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/base/statistics.rs b/src/base/statistics.rs index 9f0e0ee6..bf2c40d8 100644 --- a/src/base/statistics.rs +++ b/src/base/statistics.rs @@ -335,12 +335,27 @@ impl> Matrix { if self.is_empty() { T::zero() } else { - let val = self.iter().cloned().fold((T::zero(), T::zero()), |a, b| { - (a.0 + b.clone() * b.clone(), a.1 + b) - }); - let denom = T::one() / crate::convert::<_, T>(self.len() as f64); - let vd = val.1 * denom.clone(); - val.0 * denom - vd.clone() * vd + // let val = self.iter().cloned().fold((T::zero(), T::zero()), |a, b| { + // (a.0 + b.clone() * b.clone(), a.1 + b) + // }); + // let denom = T::one() / crate::convert::<_, T>(self.len() as f64); + // let vd = val.1 * denom.clone(); + // val.0 * denom - vd.clone() * vd + // let mean: T = self.iter().map(|&entry| entry).sum::(); + // + // let x: Vec = (0..1000).map(|_| T::zero()).collect(); + // let s: T = x.iter().cloned().fold(T::zero(), |a, b| a + b); + + // cannot use sum since `T` is not `Sum` by trait bounds + let total_sum = self.iter().cloned().fold(T::zero(), |a, b| a + b); + let n_elements = crate::convert::<_, T>(self.len() as f64); + let mean = total_sum / n_elements.clone(); + + let variance = self.iter().cloned().fold(T::zero(), |acc, x| { + acc + (x.clone() - mean.clone()) * (x.clone() - mean.clone()) + }) / n_elements.clone(); + + variance } } diff --git a/src/base/variance_test.rs b/src/base/variance_test.rs index eec5f7e4..af5d22af 100644 --- a/src/base/variance_test.rs +++ b/src/base/variance_test.rs @@ -2,6 +2,6 @@ use crate::DVector; #[test] fn test_variance_new() { - let v = DVector::repeat(10_000, 100000000.1234); + let v = DVector::repeat(10_000, 100000000.0); assert_eq!(v.variance(), 0.0) }