1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(missing_docs)]
12 #![allow(deprecated)] // Float
14 use std::cmp::Ordering::{self, Equal, Greater, Less};
17 fn local_cmp(x: f64, y: f64) -> Ordering {
18 // arbitrarily decide that NaNs are larger than everything.
21 } else if x.is_nan() {
32 fn local_sort(v: &mut [f64]) {
33 v.sort_by(|x: &f64, y: &f64| local_cmp(*x, *y));
36 /// Trait that provides simple descriptive statistics on a univariate set of numeric samples.
38 /// Sum of the samples.
40 /// Note: this method sacrifices performance at the altar of accuracy
41 /// Depends on IEEE-754 arithmetic guarantees. See proof of correctness at:
42 /// ["Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric
43 /// Predicates"][paper]
45 /// [paper]: http://www.cs.cmu.edu/~quake-papers/robust-arithmetic.ps
48 /// Minimum value of the samples.
51 /// Maximum value of the samples.
54 /// Arithmetic mean (average) of the samples: sum divided by sample-count.
56 /// See: <https://en.wikipedia.org/wiki/Arithmetic_mean>
57 fn mean(&self) -> f64;
59 /// Median of the samples: value separating the lower half of the samples from the higher half.
60 /// Equal to `self.percentile(50.0)`.
62 /// See: <https://en.wikipedia.org/wiki/Median>
63 fn median(&self) -> f64;
65 /// Variance of the samples: bias-corrected mean of the squares of the differences of each
66 /// sample from the sample mean. Note that this calculates the _sample variance_ rather than the
67 /// population variance, which is assumed to be unknown. It therefore corrects the `(n-1)/n`
68 /// bias that would appear if we calculated a population variance, by dividing by `(n-1)` rather
71 /// See: <https://en.wikipedia.org/wiki/Variance>
74 /// Standard deviation: the square root of the sample variance.
76 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
77 /// `median_abs_dev` for unknown distributions.
79 /// See: <https://en.wikipedia.org/wiki/Standard_deviation>
80 fn std_dev(&self) -> f64;
82 /// Standard deviation as a percent of the mean value. See `std_dev` and `mean`.
84 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
85 /// `median_abs_dev_pct` for unknown distributions.
86 fn std_dev_pct(&self) -> f64;
88 /// Scaled median of the absolute deviations of each sample from the sample median. This is a
89 /// robust (distribution-agnostic) estimator of sample variability. Use this in preference to
90 /// `std_dev` if you cannot assume your sample is normally distributed. Note that this is scaled
91 /// by the constant `1.4826` to allow its use as a consistent estimator for the standard
94 /// See: <http://en.wikipedia.org/wiki/Median_absolute_deviation>
95 fn median_abs_dev(&self) -> f64;
97 /// Median absolute deviation as a percent of the median. See `median_abs_dev` and `median`.
98 fn median_abs_dev_pct(&self) -> f64;
100 /// Percentile: the value below which `pct` percent of the values in `self` fall. For example,
101 /// percentile(95.0) will return the value `v` such that 95% of the samples `s` in `self`
102 /// satisfy `s <= v`.
104 /// Calculated by linear interpolation between closest ranks.
106 /// See: <http://en.wikipedia.org/wiki/Percentile>
107 fn percentile(&self, pct: f64) -> f64;
109 /// Quartiles of the sample: three values that divide the sample into four equal groups, each
110 /// with 1/4 of the data. The middle value is the median. See `median` and `percentile`. This
111 /// function may calculate the 3 quartiles more efficiently than 3 calls to `percentile`, but
112 /// is otherwise equivalent.
114 /// See also: <https://en.wikipedia.org/wiki/Quartile>
115 fn quartiles(&self) -> (f64, f64, f64);
117 /// Inter-quartile range: the difference between the 25th percentile (1st quartile) and the 75th
118 /// percentile (3rd quartile). See `quartiles`.
120 /// See also: <https://en.wikipedia.org/wiki/Interquartile_range>
121 fn iqr(&self) -> f64;
124 /// Extracted collection of all the summary statistics of a sample set.
125 #[derive(Clone, PartialEq, Copy)]
126 #[allow(missing_docs)]
135 pub std_dev_pct: f64,
136 pub median_abs_dev: f64,
137 pub median_abs_dev_pct: f64,
138 pub quartiles: (f64, f64, f64),
143 /// Construct a new summary of a sample set.
144 pub fn new(samples: &[f64]) -> Summary {
149 mean: samples.mean(),
150 median: samples.median(),
152 std_dev: samples.std_dev(),
153 std_dev_pct: samples.std_dev_pct(),
154 median_abs_dev: samples.median_abs_dev(),
155 median_abs_dev_pct: samples.median_abs_dev_pct(),
156 quartiles: samples.quartiles(),
162 impl Stats for [f64] {
163 // FIXME #11059 handle NaN, inf and overflow
164 fn sum(&self) -> f64 {
165 let mut partials = vec![];
170 // This inner loop applies `hi`/`lo` summation to each
171 // partial so that the list of partial sums remains exact.
172 for i in 0..partials.len() {
173 let mut y: f64 = partials[i];
174 if x.abs() < y.abs() {
175 mem::swap(&mut x, &mut y);
177 // Rounded `x+y` is stored in `hi` with round-off stored in
178 // `lo`. Together `hi+lo` are exactly equal to `x+y`.
180 let lo = y - (hi - x);
187 if j >= partials.len() {
191 partials.truncate(j + 1);
195 partials.iter().fold(zero, |p, q| p + *q)
198 fn min(&self) -> f64 {
199 assert!(!self.is_empty());
200 self.iter().fold(self[0], |p, q| p.min(*q))
203 fn max(&self) -> f64 {
204 assert!(!self.is_empty());
205 self.iter().fold(self[0], |p, q| p.max(*q))
208 fn mean(&self) -> f64 {
209 assert!(!self.is_empty());
210 self.sum() / (self.len() as f64)
213 fn median(&self) -> f64 {
214 self.percentile(50 as f64)
217 fn var(&self) -> f64 {
221 let mean = self.mean();
222 let mut v: f64 = 0.0;
227 // NB: this is _supposed to be_ len-1, not len. If you
228 // change it back to len, you will be calculating a
229 // population variance, not a sample variance.
230 let denom = (self.len() - 1) as f64;
235 fn std_dev(&self) -> f64 {
239 fn std_dev_pct(&self) -> f64 {
240 let hundred = 100 as f64;
241 (self.std_dev() / self.mean()) * hundred
244 fn median_abs_dev(&self) -> f64 {
245 let med = self.median();
246 let abs_devs: Vec<f64> = self.iter().map(|&v| (med - v).abs()).collect();
247 // This constant is derived by smarter statistics brains than me, but it is
248 // consistent with how R and other packages treat the MAD.
250 abs_devs.median() * number
253 fn median_abs_dev_pct(&self) -> f64 {
254 let hundred = 100 as f64;
255 (self.median_abs_dev() / self.median()) * hundred
258 fn percentile(&self, pct: f64) -> f64 {
259 let mut tmp = self.to_vec();
260 local_sort(&mut tmp);
261 percentile_of_sorted(&tmp, pct)
264 fn quartiles(&self) -> (f64, f64, f64) {
265 let mut tmp = self.to_vec();
266 local_sort(&mut tmp);
268 let a = percentile_of_sorted(&tmp, first);
270 let b = percentile_of_sorted(&tmp, second);
272 let c = percentile_of_sorted(&tmp, third);
276 fn iqr(&self) -> f64 {
277 let (a, _, c) = self.quartiles();
283 // Helper function: extract a value representing the `pct` percentile of a sorted sample-set, using
284 // linear interpolation. If samples are not sorted, return nonsensical value.
285 fn percentile_of_sorted(sorted_samples: &[f64], pct: f64) -> f64 {
286 assert!(!sorted_samples.is_empty());
287 if sorted_samples.len() == 1 {
288 return sorted_samples[0];
291 assert!(zero <= pct);
292 let hundred = 100f64;
293 assert!(pct <= hundred);
295 return sorted_samples[sorted_samples.len() - 1];
297 let length = (sorted_samples.len() - 1) as f64;
298 let rank = (pct / hundred) * length;
299 let lrank = rank.floor();
300 let d = rank - lrank;
301 let n = lrank as usize;
302 let lo = sorted_samples[n];
303 let hi = sorted_samples[n + 1];
308 /// Winsorize a set of samples, replacing values above the `100-pct` percentile
309 /// and below the `pct` percentile with those percentiles themselves. This is a
310 /// way of minimizing the effect of outliers, at the cost of biasing the sample.
311 /// It differs from trimming in that it does not change the number of samples,
312 /// just changes the values of those that are outliers.
314 /// See: <http://en.wikipedia.org/wiki/Winsorising>
315 pub fn winsorize(samples: &mut [f64], pct: f64) {
316 let mut tmp = samples.to_vec();
317 local_sort(&mut tmp);
318 let lo = percentile_of_sorted(&tmp, pct);
319 let hundred = 100 as f64;
320 let hi = percentile_of_sorted(&tmp, hundred - pct);
321 for samp in samples {
324 } else if *samp < lo {
330 // Test vectors generated from R, using the script src/etc/stat-test-vectors.r.
337 use std::io::prelude::*;
340 macro_rules! assert_approx_eq {
341 ($a:expr, $b:expr) => ({
342 let (a, b) = (&$a, &$b);
343 assert!((*a - *b).abs() < 1.0e-6,
344 "{} is not approximately equal to {}", *a, *b);
348 fn check(samples: &[f64], summ: &Summary) {
350 let summ2 = Summary::new(samples);
352 let mut w = io::sink();
354 (write!(w, "\n")).unwrap();
356 assert_eq!(summ.sum, summ2.sum);
357 assert_eq!(summ.min, summ2.min);
358 assert_eq!(summ.max, summ2.max);
359 assert_eq!(summ.mean, summ2.mean);
360 assert_eq!(summ.median, summ2.median);
362 // We needed a few more digits to get exact equality on these
363 // but they're within float epsilon, which is 1.0e-6.
364 assert_approx_eq!(summ.var, summ2.var);
365 assert_approx_eq!(summ.std_dev, summ2.std_dev);
366 assert_approx_eq!(summ.std_dev_pct, summ2.std_dev_pct);
367 assert_approx_eq!(summ.median_abs_dev, summ2.median_abs_dev);
368 assert_approx_eq!(summ.median_abs_dev_pct, summ2.median_abs_dev_pct);
370 assert_eq!(summ.quartiles, summ2.quartiles);
371 assert_eq!(summ.iqr, summ2.iqr);
375 fn test_min_max_nan() {
376 let xs = &[1.0, 2.0, f64::NAN, 3.0, 4.0];
377 let summary = Summary::new(xs);
378 assert_eq!(summary.min, 1.0);
379 assert_eq!(summary.max, 4.0);
384 let val = &[958.0000000000, 924.0000000000];
385 let summ = &Summary {
386 sum: 1882.0000000000,
389 mean: 941.0000000000,
390 median: 941.0000000000,
392 std_dev: 24.0416305603,
393 std_dev_pct: 2.5549022912,
394 median_abs_dev: 25.2042000000,
395 median_abs_dev_pct: 2.6784484591,
396 quartiles: (932.5000000000, 941.0000000000, 949.5000000000),
402 fn test_norm10narrow() {
415 let summ = &Summary {
416 sum: 9996.0000000000,
418 max: 1217.0000000000,
419 mean: 999.6000000000,
420 median: 970.5000000000,
421 var: 16050.7111111111,
422 std_dev: 126.6914010938,
423 std_dev_pct: 12.6742097933,
424 median_abs_dev: 102.2994000000,
425 median_abs_dev_pct: 10.5408964451,
426 quartiles: (956.7500000000, 970.5000000000, 1078.7500000000),
432 fn test_norm10medium() {
445 let summ = &Summary {
446 sum: 8653.0000000000,
448 max: 1084.0000000000,
449 mean: 865.3000000000,
450 median: 911.5000000000,
451 var: 48628.4555555556,
452 std_dev: 220.5186059170,
453 std_dev_pct: 25.4846418487,
454 median_abs_dev: 195.7032000000,
455 median_abs_dev_pct: 21.4704552935,
456 quartiles: (771.0000000000, 911.5000000000, 1017.2500000000),
462 fn test_norm10wide() {
475 let summ = &Summary {
476 sum: 9349.0000000000,
478 max: 1591.0000000000,
479 mean: 934.9000000000,
480 median: 913.5000000000,
481 var: 239208.9888888889,
482 std_dev: 489.0899599142,
483 std_dev_pct: 52.3146817750,
484 median_abs_dev: 611.5725000000,
485 median_abs_dev_pct: 66.9482758621,
486 quartiles: (567.2500000000, 913.5000000000, 1331.2500000000),
492 fn test_norm25verynarrow() {
520 let summ = &Summary {
521 sum: 24926.0000000000,
523 max: 1040.0000000000,
524 mean: 997.0400000000,
525 median: 998.0000000000,
527 std_dev: 19.8294393937,
528 std_dev_pct: 1.9888308788,
529 median_abs_dev: 22.2390000000,
530 median_abs_dev_pct: 2.2283567134,
531 quartiles: (983.0000000000, 998.0000000000, 1013.0000000000),
550 let summ = &Summary {
555 median: 11.5000000000,
557 std_dev: 16.9643416875,
558 std_dev_pct: 101.5828843560,
559 median_abs_dev: 13.3434000000,
560 median_abs_dev_pct: 116.0295652174,
561 quartiles: (4.2500000000, 11.5000000000, 22.5000000000),
580 let summ = &Summary {
585 median: 24.5000000000,
587 std_dev: 19.5848580967,
588 std_dev_pct: 74.4671410520,
589 median_abs_dev: 22.9803000000,
590 median_abs_dev_pct: 93.7971428571,
591 quartiles: (9.5000000000, 24.5000000000, 36.5000000000),
610 let summ = &Summary {
615 median: 22.0000000000,
617 std_dev: 21.4050876611,
618 std_dev_pct: 88.4507754589,
619 median_abs_dev: 21.4977000000,
620 median_abs_dev_pct: 97.7168181818,
621 quartiles: (7.7500000000, 22.0000000000, 35.0000000000),
655 let summ = &Summary {
660 median: 19.0000000000,
662 std_dev: 24.5161851301,
663 std_dev_pct: 103.3565983562,
664 median_abs_dev: 19.2738000000,
665 median_abs_dev_pct: 101.4410526316,
666 quartiles: (6.0000000000, 19.0000000000, 31.0000000000),
700 let summ = &Summary {
705 median: 20.0000000000,
707 std_dev: 4.5650848842,
708 std_dev_pct: 22.2037202539,
709 median_abs_dev: 5.9304000000,
710 median_abs_dev_pct: 29.6520000000,
711 quartiles: (17.0000000000, 20.0000000000, 24.0000000000),
717 fn test_pois25lambda30() {
745 let summ = &Summary {
750 median: 32.0000000000,
752 std_dev: 5.1568724372,
753 std_dev_pct: 16.3814245145,
754 median_abs_dev: 5.9304000000,
755 median_abs_dev_pct: 18.5325000000,
756 quartiles: (28.0000000000, 32.0000000000, 34.0000000000),
762 fn test_pois25lambda40() {
790 let summ = &Summary {
791 sum: 1019.0000000000,
795 median: 42.0000000000,
797 std_dev: 5.8685603004,
798 std_dev_pct: 14.3978417577,
799 median_abs_dev: 5.9304000000,
800 median_abs_dev_pct: 14.1200000000,
801 quartiles: (37.0000000000, 42.0000000000, 45.0000000000),
807 fn test_pois25lambda50() {
835 let summ = &Summary {
836 sum: 1235.0000000000,
840 median: 50.0000000000,
842 std_dev: 5.6273143387,
843 std_dev_pct: 11.3913245723,
844 median_abs_dev: 4.4478000000,
845 median_abs_dev_pct: 8.8956000000,
846 quartiles: (44.0000000000, 50.0000000000, 52.0000000000),
880 let summ = &Summary {
881 sum: 1242.0000000000,
885 median: 45.0000000000,
886 var: 1015.6433333333,
887 std_dev: 31.8691595957,
888 std_dev_pct: 64.1488719719,
889 median_abs_dev: 45.9606000000,
890 median_abs_dev_pct: 102.1346666667,
891 quartiles: (29.0000000000, 45.0000000000, 79.0000000000),
899 assert_eq!([0.5f64, 3.2321f64, 1.5678f64].sum(), 5.2999);
902 fn test_sum_f64_between_ints_that_sum_to_0() {
903 assert_eq!([1e30f64, 1.2f64, -1e30f64].sum(), 1.2);
913 pub fn sum_three_items(b: &mut Bencher) {
914 b.iter(|| { [1e20f64, 1.5f64, -1e20f64].sum(); })
917 pub fn sum_many_f64(b: &mut Bencher) {
918 let nums = [-1e30f64, 1e60, 1e30, 1.0, -1e60];
919 let v = (0..500).map(|i| nums[i % 5]).collect::<Vec<_>>();
921 b.iter(|| { v.sum(); })
925 pub fn no_iter(_: &mut Bencher) {}