1 #![allow(missing_docs)]
2 #![allow(deprecated)] // Float
4 use std::cmp::Ordering::{self, Equal, Greater, Less};
7 fn local_cmp(x: f64, y: f64) -> Ordering {
8 // arbitrarily decide that NaNs are larger than everything.
11 } else if x.is_nan() {
22 fn local_sort(v: &mut [f64]) {
23 v.sort_by(|x: &f64, y: &f64| local_cmp(*x, *y));
26 /// Trait that provides simple descriptive statistics on a univariate set of numeric samples.
28 /// Sum of the samples.
30 /// Note: this method sacrifices performance at the altar of accuracy
31 /// Depends on IEEE-754 arithmetic guarantees. See proof of correctness at:
32 /// ["Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric
33 /// Predicates"][paper]
35 /// [paper]: http://www.cs.cmu.edu/~quake-papers/robust-arithmetic.ps
38 /// Minimum value of the samples.
41 /// Maximum value of the samples.
44 /// Arithmetic mean (average) of the samples: sum divided by sample-count.
46 /// See: <https://en.wikipedia.org/wiki/Arithmetic_mean>
47 fn mean(&self) -> f64;
49 /// Median of the samples: value separating the lower half of the samples from the higher half.
50 /// Equal to `self.percentile(50.0)`.
52 /// See: <https://en.wikipedia.org/wiki/Median>
53 fn median(&self) -> f64;
55 /// Variance of the samples: bias-corrected mean of the squares of the differences of each
56 /// sample from the sample mean. Note that this calculates the _sample variance_ rather than the
57 /// population variance, which is assumed to be unknown. It therefore corrects the `(n-1)/n`
58 /// bias that would appear if we calculated a population variance, by dividing by `(n-1)` rather
61 /// See: <https://en.wikipedia.org/wiki/Variance>
64 /// Standard deviation: the square root of the sample variance.
66 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
67 /// `median_abs_dev` for unknown distributions.
69 /// See: <https://en.wikipedia.org/wiki/Standard_deviation>
70 fn std_dev(&self) -> f64;
72 /// Standard deviation as a percent of the mean value. See `std_dev` and `mean`.
74 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
75 /// `median_abs_dev_pct` for unknown distributions.
76 fn std_dev_pct(&self) -> f64;
78 /// Scaled median of the absolute deviations of each sample from the sample median. This is a
79 /// robust (distribution-agnostic) estimator of sample variability. Use this in preference to
80 /// `std_dev` if you cannot assume your sample is normally distributed. Note that this is scaled
81 /// by the constant `1.4826` to allow its use as a consistent estimator for the standard
84 /// See: <http://en.wikipedia.org/wiki/Median_absolute_deviation>
85 fn median_abs_dev(&self) -> f64;
87 /// Median absolute deviation as a percent of the median. See `median_abs_dev` and `median`.
88 fn median_abs_dev_pct(&self) -> f64;
90 /// Percentile: the value below which `pct` percent of the values in `self` fall. For example,
91 /// percentile(95.0) will return the value `v` such that 95% of the samples `s` in `self`
94 /// Calculated by linear interpolation between closest ranks.
96 /// See: <http://en.wikipedia.org/wiki/Percentile>
97 fn percentile(&self, pct: f64) -> f64;
99 /// Quartiles of the sample: three values that divide the sample into four equal groups, each
100 /// with 1/4 of the data. The middle value is the median. See `median` and `percentile`. This
101 /// function may calculate the 3 quartiles more efficiently than 3 calls to `percentile`, but
102 /// is otherwise equivalent.
104 /// See also: <https://en.wikipedia.org/wiki/Quartile>
105 fn quartiles(&self) -> (f64, f64, f64);
107 /// Inter-quartile range: the difference between the 25th percentile (1st quartile) and the 75th
108 /// percentile (3rd quartile). See `quartiles`.
110 /// See also: <https://en.wikipedia.org/wiki/Interquartile_range>
111 fn iqr(&self) -> f64;
114 /// Extracted collection of all the summary statistics of a sample set.
115 #[derive(Clone, PartialEq, Copy)]
116 #[allow(missing_docs)]
125 pub std_dev_pct: f64,
126 pub median_abs_dev: f64,
127 pub median_abs_dev_pct: f64,
128 pub quartiles: (f64, f64, f64),
133 /// Construct a new summary of a sample set.
134 pub fn new(samples: &[f64]) -> Summary {
139 mean: samples.mean(),
140 median: samples.median(),
142 std_dev: samples.std_dev(),
143 std_dev_pct: samples.std_dev_pct(),
144 median_abs_dev: samples.median_abs_dev(),
145 median_abs_dev_pct: samples.median_abs_dev_pct(),
146 quartiles: samples.quartiles(),
152 impl Stats for [f64] {
153 // FIXME #11059 handle NaN, inf and overflow
154 fn sum(&self) -> f64 {
155 let mut partials = vec![];
160 // This inner loop applies `hi`/`lo` summation to each
161 // partial so that the list of partial sums remains exact.
162 for i in 0..partials.len() {
163 let mut y: f64 = partials[i];
164 if x.abs() < y.abs() {
165 mem::swap(&mut x, &mut y);
167 // Rounded `x+y` is stored in `hi` with round-off stored in
168 // `lo`. Together `hi+lo` are exactly equal to `x+y`.
170 let lo = y - (hi - x);
177 if j >= partials.len() {
181 partials.truncate(j + 1);
185 partials.iter().fold(zero, |p, q| p + *q)
188 fn min(&self) -> f64 {
189 assert!(!self.is_empty());
190 self.iter().fold(self[0], |p, q| p.min(*q))
193 fn max(&self) -> f64 {
194 assert!(!self.is_empty());
195 self.iter().fold(self[0], |p, q| p.max(*q))
198 fn mean(&self) -> f64 {
199 assert!(!self.is_empty());
200 self.sum() / (self.len() as f64)
203 fn median(&self) -> f64 {
204 self.percentile(50 as f64)
207 fn var(&self) -> f64 {
211 let mean = self.mean();
212 let mut v: f64 = 0.0;
217 // N.B., this is _supposed to be_ len-1, not len. If you
218 // change it back to len, you will be calculating a
219 // population variance, not a sample variance.
220 let denom = (self.len() - 1) as f64;
225 fn std_dev(&self) -> f64 {
229 fn std_dev_pct(&self) -> f64 {
230 let hundred = 100 as f64;
231 (self.std_dev() / self.mean()) * hundred
234 fn median_abs_dev(&self) -> f64 {
235 let med = self.median();
236 let abs_devs: Vec<f64> = self.iter().map(|&v| (med - v).abs()).collect();
237 // This constant is derived by smarter statistics brains than me, but it is
238 // consistent with how R and other packages treat the MAD.
240 abs_devs.median() * number
243 fn median_abs_dev_pct(&self) -> f64 {
244 let hundred = 100 as f64;
245 (self.median_abs_dev() / self.median()) * hundred
248 fn percentile(&self, pct: f64) -> f64 {
249 let mut tmp = self.to_vec();
250 local_sort(&mut tmp);
251 percentile_of_sorted(&tmp, pct)
254 fn quartiles(&self) -> (f64, f64, f64) {
255 let mut tmp = self.to_vec();
256 local_sort(&mut tmp);
258 let a = percentile_of_sorted(&tmp, first);
260 let b = percentile_of_sorted(&tmp, second);
262 let c = percentile_of_sorted(&tmp, third);
266 fn iqr(&self) -> f64 {
267 let (a, _, c) = self.quartiles();
272 // Helper function: extract a value representing the `pct` percentile of a sorted sample-set, using
273 // linear interpolation. If samples are not sorted, return nonsensical value.
274 fn percentile_of_sorted(sorted_samples: &[f64], pct: f64) -> f64 {
275 assert!(!sorted_samples.is_empty());
276 if sorted_samples.len() == 1 {
277 return sorted_samples[0];
280 assert!(zero <= pct);
281 let hundred = 100f64;
282 assert!(pct <= hundred);
284 return sorted_samples[sorted_samples.len() - 1];
286 let length = (sorted_samples.len() - 1) as f64;
287 let rank = (pct / hundred) * length;
288 let lrank = rank.floor();
289 let d = rank - lrank;
290 let n = lrank as usize;
291 let lo = sorted_samples[n];
292 let hi = sorted_samples[n + 1];
296 /// Winsorize a set of samples, replacing values above the `100-pct` percentile
297 /// and below the `pct` percentile with those percentiles themselves. This is a
298 /// way of minimizing the effect of outliers, at the cost of biasing the sample.
299 /// It differs from trimming in that it does not change the number of samples,
300 /// just changes the values of those that are outliers.
302 /// See: <http://en.wikipedia.org/wiki/Winsorising>
303 pub fn winsorize(samples: &mut [f64], pct: f64) {
304 let mut tmp = samples.to_vec();
305 local_sort(&mut tmp);
306 let lo = percentile_of_sorted(&tmp, pct);
307 let hundred = 100 as f64;
308 let hi = percentile_of_sorted(&tmp, hundred - pct);
309 for samp in samples {
312 } else if *samp < lo {
318 // Test vectors generated from R, using the script src/etc/stat-test-vectors.r.
322 use crate::stats::Stats;
323 use crate::stats::Summary;
325 use std::io::prelude::*;
328 macro_rules! assert_approx_eq {
329 ($a: expr, $b: expr) => {{
330 let (a, b) = (&$a, &$b);
332 (*a - *b).abs() < 1.0e-6,
333 "{} is not approximately equal to {}",
340 fn check(samples: &[f64], summ: &Summary) {
341 let summ2 = Summary::new(samples);
343 let mut w = io::sink();
345 (write!(w, "\n")).unwrap();
347 assert_eq!(summ.sum, summ2.sum);
348 assert_eq!(summ.min, summ2.min);
349 assert_eq!(summ.max, summ2.max);
350 assert_eq!(summ.mean, summ2.mean);
351 assert_eq!(summ.median, summ2.median);
353 // We needed a few more digits to get exact equality on these
354 // but they're within float epsilon, which is 1.0e-6.
355 assert_approx_eq!(summ.var, summ2.var);
356 assert_approx_eq!(summ.std_dev, summ2.std_dev);
357 assert_approx_eq!(summ.std_dev_pct, summ2.std_dev_pct);
358 assert_approx_eq!(summ.median_abs_dev, summ2.median_abs_dev);
359 assert_approx_eq!(summ.median_abs_dev_pct, summ2.median_abs_dev_pct);
361 assert_eq!(summ.quartiles, summ2.quartiles);
362 assert_eq!(summ.iqr, summ2.iqr);
366 fn test_min_max_nan() {
367 let xs = &[1.0, 2.0, f64::NAN, 3.0, 4.0];
368 let summary = Summary::new(xs);
369 assert_eq!(summary.min, 1.0);
370 assert_eq!(summary.max, 4.0);
375 let val = &[958.0000000000, 924.0000000000];
376 let summ = &Summary {
377 sum: 1882.0000000000,
380 mean: 941.0000000000,
381 median: 941.0000000000,
383 std_dev: 24.0416305603,
384 std_dev_pct: 2.5549022912,
385 median_abs_dev: 25.2042000000,
386 median_abs_dev_pct: 2.6784484591,
387 quartiles: (932.5000000000, 941.0000000000, 949.5000000000),
393 fn test_norm10narrow() {
406 let summ = &Summary {
407 sum: 9996.0000000000,
409 max: 1217.0000000000,
410 mean: 999.6000000000,
411 median: 970.5000000000,
412 var: 16050.7111111111,
413 std_dev: 126.6914010938,
414 std_dev_pct: 12.6742097933,
415 median_abs_dev: 102.2994000000,
416 median_abs_dev_pct: 10.5408964451,
417 quartiles: (956.7500000000, 970.5000000000, 1078.7500000000),
423 fn test_norm10medium() {
436 let summ = &Summary {
437 sum: 8653.0000000000,
439 max: 1084.0000000000,
440 mean: 865.3000000000,
441 median: 911.5000000000,
442 var: 48628.4555555556,
443 std_dev: 220.5186059170,
444 std_dev_pct: 25.4846418487,
445 median_abs_dev: 195.7032000000,
446 median_abs_dev_pct: 21.4704552935,
447 quartiles: (771.0000000000, 911.5000000000, 1017.2500000000),
453 fn test_norm10wide() {
466 let summ = &Summary {
467 sum: 9349.0000000000,
469 max: 1591.0000000000,
470 mean: 934.9000000000,
471 median: 913.5000000000,
472 var: 239208.9888888889,
473 std_dev: 489.0899599142,
474 std_dev_pct: 52.3146817750,
475 median_abs_dev: 611.5725000000,
476 median_abs_dev_pct: 66.9482758621,
477 quartiles: (567.2500000000, 913.5000000000, 1331.2500000000),
483 fn test_norm25verynarrow() {
511 let summ = &Summary {
512 sum: 24926.0000000000,
514 max: 1040.0000000000,
515 mean: 997.0400000000,
516 median: 998.0000000000,
518 std_dev: 19.8294393937,
519 std_dev_pct: 1.9888308788,
520 median_abs_dev: 22.2390000000,
521 median_abs_dev_pct: 2.2283567134,
522 quartiles: (983.0000000000, 998.0000000000, 1013.0000000000),
541 let summ = &Summary {
546 median: 11.5000000000,
548 std_dev: 16.9643416875,
549 std_dev_pct: 101.5828843560,
550 median_abs_dev: 13.3434000000,
551 median_abs_dev_pct: 116.0295652174,
552 quartiles: (4.2500000000, 11.5000000000, 22.5000000000),
571 let summ = &Summary {
576 median: 24.5000000000,
578 std_dev: 19.5848580967,
579 std_dev_pct: 74.4671410520,
580 median_abs_dev: 22.9803000000,
581 median_abs_dev_pct: 93.7971428571,
582 quartiles: (9.5000000000, 24.5000000000, 36.5000000000),
601 let summ = &Summary {
606 median: 22.0000000000,
608 std_dev: 21.4050876611,
609 std_dev_pct: 88.4507754589,
610 median_abs_dev: 21.4977000000,
611 median_abs_dev_pct: 97.7168181818,
612 quartiles: (7.7500000000, 22.0000000000, 35.0000000000),
646 let summ = &Summary {
651 median: 19.0000000000,
653 std_dev: 24.5161851301,
654 std_dev_pct: 103.3565983562,
655 median_abs_dev: 19.2738000000,
656 median_abs_dev_pct: 101.4410526316,
657 quartiles: (6.0000000000, 19.0000000000, 31.0000000000),
691 let summ = &Summary {
696 median: 20.0000000000,
698 std_dev: 4.5650848842,
699 std_dev_pct: 22.2037202539,
700 median_abs_dev: 5.9304000000,
701 median_abs_dev_pct: 29.6520000000,
702 quartiles: (17.0000000000, 20.0000000000, 24.0000000000),
708 fn test_pois25lambda30() {
736 let summ = &Summary {
741 median: 32.0000000000,
743 std_dev: 5.1568724372,
744 std_dev_pct: 16.3814245145,
745 median_abs_dev: 5.9304000000,
746 median_abs_dev_pct: 18.5325000000,
747 quartiles: (28.0000000000, 32.0000000000, 34.0000000000),
753 fn test_pois25lambda40() {
781 let summ = &Summary {
782 sum: 1019.0000000000,
786 median: 42.0000000000,
788 std_dev: 5.8685603004,
789 std_dev_pct: 14.3978417577,
790 median_abs_dev: 5.9304000000,
791 median_abs_dev_pct: 14.1200000000,
792 quartiles: (37.0000000000, 42.0000000000, 45.0000000000),
798 fn test_pois25lambda50() {
826 let summ = &Summary {
827 sum: 1235.0000000000,
831 median: 50.0000000000,
833 std_dev: 5.6273143387,
834 std_dev_pct: 11.3913245723,
835 median_abs_dev: 4.4478000000,
836 median_abs_dev_pct: 8.8956000000,
837 quartiles: (44.0000000000, 50.0000000000, 52.0000000000),
871 let summ = &Summary {
872 sum: 1242.0000000000,
876 median: 45.0000000000,
877 var: 1015.6433333333,
878 std_dev: 31.8691595957,
879 std_dev_pct: 64.1488719719,
880 median_abs_dev: 45.9606000000,
881 median_abs_dev_pct: 102.1346666667,
882 quartiles: (29.0000000000, 45.0000000000, 79.0000000000),
890 assert_eq!([0.5f64, 3.2321f64, 1.5678f64].sum(), 5.2999);
893 fn test_sum_f64_between_ints_that_sum_to_0() {
894 assert_eq!([1e30f64, 1.2f64, -1e30f64].sum(), 1.2);
901 use self::test::Bencher;
902 use crate::stats::Stats;
905 pub fn sum_three_items(b: &mut Bencher) {
907 [1e20f64, 1.5f64, -1e20f64].sum();
911 pub fn sum_many_f64(b: &mut Bencher) {
912 let nums = [-1e30f64, 1e60, 1e30, 1.0, -1e60];
913 let v = (0..500).map(|i| nums[i % 5]).collect::<Vec<_>>();
921 pub fn no_iter(_: &mut Bencher) {}