surrealdb_core/fnc/util/math/
variance.rs

1use super::mean::Mean;
2use crate::fnc::util::math::ToFloat;
3use crate::val::Number;
4
5pub trait Variance {
6	/// Population Variance of Data
7	/// O(n) time complex
8	fn variance(self, sample: bool) -> f64;
9}
10
11impl Variance for Vec<Number> {
12	fn variance(self, sample: bool) -> f64 {
13		variance(&self, self.mean(), sample)
14	}
15}
16
17// This function is exposed to optimise the pearson distance calculation.
18// As the mean of the vector is already calculated, we pass it as a parameter
19// rather than recalculating it.
20pub(super) fn variance<T>(v: &[T], mean: f64, sample: bool) -> f64
21where
22	T: ToFloat,
23{
24	match v.len() {
25		0 => f64::NAN,
26		1 => 0.0,
27		len => {
28			let len = (len - sample as usize) as f64;
29			v.iter().map(|x| (x.to_float() - mean).powi(2)).sum::<f64>() / len
30		}
31	}
32}