initial, unoptimized algoritm

This commit is contained in:
Vasil Nikolov 2023-04-24 01:22:57 +03:00
parent 029bbc9ecc
commit 032002dce9
2 changed files with 22 additions and 7 deletions

View File

@ -335,12 +335,27 @@ impl<T: Scalar, R: Dim, C: Dim, S: RawStorage<T, R, C>> Matrix<T, R, C, S> {
if self.is_empty() { if self.is_empty() {
T::zero() T::zero()
} else { } else {
let val = self.iter().cloned().fold((T::zero(), T::zero()), |a, b| { // let val = self.iter().cloned().fold((T::zero(), T::zero()), |a, b| {
(a.0 + b.clone() * b.clone(), a.1 + b) // (a.0 + b.clone() * b.clone(), a.1 + b)
}); // });
let denom = T::one() / crate::convert::<_, T>(self.len() as f64); // let denom = T::one() / crate::convert::<_, T>(self.len() as f64);
let vd = val.1 * denom.clone(); // let vd = val.1 * denom.clone();
val.0 * denom - vd.clone() * vd // val.0 * denom - vd.clone() * vd
// let mean: T = self.iter().map(|&entry| entry).sum::<T>();
//
// let x: Vec<T> = (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
} }
} }

View File

@ -2,6 +2,6 @@
use crate::DVector; use crate::DVector;
#[test] #[test]
fn test_variance_new() { 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) assert_eq!(v.variance(), 0.0)
} }