Skip to main content

lib_jsl_statistics/
descriptive.rs

1//! Descriptive statistics of a sample.
2//!
3//! See the book entry [Descriptive statistics](https://jwkunz.github.io/lib_jsl/book/statistics/descriptive.html).
4
5use lib_jsl_core::ErrorsJSL;
6
7fn non_empty(x: &[f64]) -> Result<(), ErrorsJSL> {
8    if x.is_empty() {
9        return Err(ErrorsJSL::InvalidInputRange("The sample must not be empty."));
10    }
11    Ok(())
12}
13
14// ANCHOR: mean_variance
15/// The arithmetic mean.
16pub fn mean(x: &[f64]) -> Result<f64, ErrorsJSL> {
17    non_empty(x)?;
18    // Pairwise-free compensated (Neumaier) summation keeps the mean accurate for long samples.
19    let (mut sum, mut compensation) = (0.0f64, 0.0f64);
20    for &v in x {
21        let t = sum + v;
22        compensation += if sum.abs() >= v.abs() { (sum - t) + v } else { (v - t) + sum };
23        sum = t;
24    }
25    Ok((sum + compensation) / x.len() as f64)
26}
27
28/// The variance with `ddof` delta degrees of freedom: `Σ(x − x̄)² / (n − ddof)` (1 for the
29/// unbiased sample variance, 0 for the population variance). Two-pass for accuracy.
30pub fn variance(x: &[f64], ddof: usize) -> Result<f64, ErrorsJSL> {
31    if x.len() <= ddof {
32        return Err(ErrorsJSL::InvalidInputRange("Need more samples than delta degrees of freedom."));
33    }
34    let m = mean(x)?;
35    let (sum_sq, sum) = x.iter().fold((0.0, 0.0), |(s2, s1), &v| (s2 + (v - m) * (v - m), s1 + (v - m)));
36    // The second term corrects the rounding left in the mean.
37    Ok((sum_sq - sum * sum / x.len() as f64) / (x.len() - ddof) as f64)
38}
39// ANCHOR_END: mean_variance
40
41/// The standard deviation with `ddof` delta degrees of freedom.
42pub fn standard_deviation(x: &[f64], ddof: usize) -> Result<f64, ErrorsJSL> {
43    Ok(variance(x, ddof)?.sqrt())
44}
45
46/// The standard error of the mean, `s / √n`.
47pub fn standard_error(x: &[f64]) -> Result<f64, ErrorsJSL> {
48    Ok(standard_deviation(x, 1)? / (x.len() as f64).sqrt())
49}
50
51/// The weighted mean `Σ wᵢxᵢ / Σ wᵢ`.
52pub fn weighted_mean(x: &[f64], weights: &[f64]) -> Result<f64, ErrorsJSL> {
53    if x.len() != weights.len() {
54        return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), weights.len())));
55    }
56    let total: f64 = weights.iter().sum();
57    if !(total > 0.0) || weights.iter().any(|w| *w < 0.0) {
58        return Err(ErrorsJSL::InvalidInputRange("Weights must be non-negative with a positive sum."));
59    }
60    Ok(x.iter().zip(weights).map(|(a, w)| a * w).sum::<f64>() / total)
61}
62
63/// The geometric mean (all values positive).
64pub fn geometric_mean(x: &[f64]) -> Result<f64, ErrorsJSL> {
65    non_empty(x)?;
66    if x.iter().any(|v| !(*v > 0.0)) {
67        return Err(ErrorsJSL::InvalidInputRange("The geometric mean needs positive values."));
68    }
69    Ok((x.iter().map(|v| v.ln()).sum::<f64>() / x.len() as f64).exp())
70}
71
72/// The harmonic mean (all values positive).
73pub fn harmonic_mean(x: &[f64]) -> Result<f64, ErrorsJSL> {
74    non_empty(x)?;
75    if x.iter().any(|v| !(*v > 0.0)) {
76        return Err(ErrorsJSL::InvalidInputRange("The harmonic mean needs positive values."));
77    }
78    Ok(x.len() as f64 / x.iter().map(|v| 1.0 / v).sum::<f64>())
79}
80
81fn sorted(x: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
82    non_empty(x)?;
83    if x.iter().any(|v| v.is_nan()) {
84        return Err(ErrorsJSL::InvalidInputRange("The sample contains NaN."));
85    }
86    let mut s = x.to_vec();
87    s.sort_by(f64::total_cmp);
88    Ok(s)
89}
90
91// ANCHOR: quantile
92fn quantile_sorted(s: &[f64], p: f64) -> f64 {
93    let h = (s.len() - 1) as f64 * p;
94    let (lo, frac) = (h.floor() as usize, h - h.floor());
95    if lo + 1 < s.len() { s[lo] + frac * (s[lo + 1] - s[lo]) } else { s[lo] }
96}
97// ANCHOR_END: quantile
98
99/// The `p`-quantile (`0 ≤ p ≤ 1`) by linear interpolation between order statistics at
100/// `h = (n − 1)p` (Hyndman and Fan type 7, the default of R and NumPy).
101pub fn quantile(x: &[f64], p: f64) -> Result<f64, ErrorsJSL> {
102    if !(0.0..=1.0).contains(&p) {
103        return Err(ErrorsJSL::InvalidInputRange("The quantile probability must lie in [0, 1]."));
104    }
105    Ok(quantile_sorted(&sorted(x)?, p))
106}
107
108/// The median.
109pub fn median(x: &[f64]) -> Result<f64, ErrorsJSL> {
110    quantile(x, 0.5)
111}
112
113/// The interquartile range `Q3 − Q1`.
114pub fn interquartile_range(x: &[f64]) -> Result<f64, ErrorsJSL> {
115    let s = sorted(x)?;
116    Ok(quantile_sorted(&s, 0.75) - quantile_sorted(&s, 0.25))
117}
118
119/// The median absolute deviation `median(|x − median(x)|)`, scaled by `scale` (1.4826 makes it a
120/// consistent estimator of σ for normal data).
121pub fn median_absolute_deviation(x: &[f64], scale: f64) -> Result<f64, ErrorsJSL> {
122    let m = median(x)?;
123    Ok(scale * median(&x.iter().map(|v| (v - m).abs()).collect::<Vec<_>>())?)
124}
125
126/// The sample skewness `g₁ = m₃ / m₂^{3/2}` (biased, as `scipy.stats.skew` by default).
127pub fn skewness(x: &[f64]) -> Result<f64, ErrorsJSL> {
128    let m = mean(x)?;
129    let n = x.len() as f64;
130    let m2 = x.iter().map(|v| (v - m).powi(2)).sum::<f64>() / n;
131    let m3 = x.iter().map(|v| (v - m).powi(3)).sum::<f64>() / n;
132    Ok(m3 / m2.powf(1.5))
133}
134
135/// The excess kurtosis `g₂ = m₄ / m₂² − 3` (biased; 0 for a normal distribution).
136pub fn excess_kurtosis(x: &[f64]) -> Result<f64, ErrorsJSL> {
137    let m = mean(x)?;
138    let n = x.len() as f64;
139    let m2 = x.iter().map(|v| (v - m).powi(2)).sum::<f64>() / n;
140    let m4 = x.iter().map(|v| (v - m).powi(4)).sum::<f64>() / n;
141    Ok(m4 / (m2 * m2) - 3.0)
142}
143
144/// A summary of a sample.
145#[derive(Debug, Clone, PartialEq)]
146pub struct Summary {
147    pub count: usize,
148    pub mean: f64,
149    /// Sample standard deviation (`ddof = 1`; NaN for a single value).
150    pub standard_deviation: f64,
151    pub minimum: f64,
152    pub first_quartile: f64,
153    pub median: f64,
154    pub third_quartile: f64,
155    pub maximum: f64,
156}
157
158/// Count, mean, standard deviation and the five-number summary.
159pub fn summary(x: &[f64]) -> Result<Summary, ErrorsJSL> {
160    let s = sorted(x)?;
161    Ok(Summary {
162        count: s.len(),
163        mean: mean(&s)?,
164        standard_deviation: if s.len() > 1 { standard_deviation(&s, 1)? } else { f64::NAN },
165        minimum: s[0],
166        first_quartile: quantile_sorted(&s, 0.25),
167        median: quantile_sorted(&s, 0.5),
168        third_quartile: quantile_sorted(&s, 0.75),
169        maximum: s[s.len() - 1],
170    })
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    #[test]
178    fn location_and_spread() {
179        let x = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
180        assert_eq!(mean(&x).unwrap(), 5.0);
181        assert_eq!(variance(&x, 0).unwrap(), 4.0);
182        assert!((variance(&x, 1).unwrap() - 32.0 / 7.0).abs() < 1e-15);
183        assert_eq!(standard_deviation(&x, 0).unwrap(), 2.0);
184        assert_eq!(median(&x).unwrap(), 4.5);
185        assert_eq!(quantile(&x, 0.25).unwrap(), 4.0);
186        assert_eq!(quantile(&[1.0, 2.0, 3.0, 4.0], 0.1).unwrap(), 1.3); // type 7
187        assert_eq!(interquartile_range(&x).unwrap(), 1.5);
188        assert_eq!(median_absolute_deviation(&x, 1.0).unwrap(), 0.5);
189        assert!((geometric_mean(&[1.0, 4.0, 16.0]).unwrap() - 4.0).abs() < 1e-14);
190        assert!((harmonic_mean(&[1.0, 2.0, 4.0]).unwrap() - 12.0 / 7.0).abs() < 1e-15);
191        assert_eq!(weighted_mean(&[1.0, 3.0], &[3.0, 1.0]).unwrap(), 1.5);
192        assert!(mean(&[]).is_err() && variance(&[1.0], 1).is_err() && geometric_mean(&[1.0, -1.0]).is_err());
193    }
194
195    #[test]
196    fn variance_is_accurate_with_a_large_offset_and_shape_statistics() {
197        // A naive Σx² − n x̄² formula loses every digit here.
198        let x: Vec<f64> = (0..1000).map(|i| 1e9 + (i % 10) as f64).collect();
199        assert!((variance(&x, 0).unwrap() - 8.25).abs() < 1e-6);
200        // A symmetric sample has zero skewness; uniform-ish data has negative excess kurtosis.
201        let y: Vec<f64> = (0..101).map(|i| i as f64).collect();
202        assert!(skewness(&y).unwrap().abs() < 1e-12);
203        assert!((excess_kurtosis(&y).unwrap() + 1.2).abs() < 0.01);
204        assert!(skewness(&[1.0, 1.0, 1.0, 10.0]).unwrap() > 1.0);
205        let s = summary(&[3.0, 1.0, 2.0]).unwrap();
206        assert_eq!((s.count, s.minimum, s.median, s.maximum, s.standard_deviation), (3, 1.0, 2.0, 3.0, 1.0));
207    }
208}