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_doc)]
17 use collections::hashmap;
19 // NB: this can probably be rewritten in terms of num::Num
20 // to be less f64-specific.
22 fn f64_cmp(x: f64, y: f64) -> Ordering {
23 // arbitrarily decide that NaNs are larger than everything.
26 } else if x.is_nan() {
37 fn f64_sort(v: &mut [f64]) {
38 v.sort_by(|x: &f64, y: &f64| f64_cmp(*x, *y));
41 /// Trait that provides simple descriptive statistics on a univariate set of numeric samples.
44 /// Sum of the samples.
46 /// Note: this method sacrifices performance at the altar of accuracy
47 /// Depends on IEEE-754 arithmetic guarantees. See proof of correctness at:
48 /// ["Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates"]
49 /// (http://www.cs.cmu.edu/~quake-papers/robust-arithmetic.ps)
50 /// *Discrete & Computational Geometry 18*, 3 (Oct 1997), 305-363, Shewchuk J.R.
53 /// Minimum value of the samples.
56 /// Maximum value of the samples.
59 /// Arithmetic mean (average) of the samples: sum divided by sample-count.
61 /// See: https://en.wikipedia.org/wiki/Arithmetic_mean
64 /// Median of the samples: value separating the lower half of the samples from the higher half.
65 /// Equal to `self.percentile(50.0)`.
67 /// See: https://en.wikipedia.org/wiki/Median
68 fn median(self) -> f64;
70 /// Variance of the samples: bias-corrected mean of the squares of the differences of each
71 /// sample from the sample mean. Note that this calculates the _sample variance_ rather than the
72 /// population variance, which is assumed to be unknown. It therefore corrects the `(n-1)/n`
73 /// bias that would appear if we calculated a population variance, by dividing by `(n-1)` rather
76 /// See: https://en.wikipedia.org/wiki/Variance
79 /// Standard deviation: the square root of the sample variance.
81 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
82 /// `median_abs_dev` for unknown distributions.
84 /// See: https://en.wikipedia.org/wiki/Standard_deviation
85 fn std_dev(self) -> f64;
87 /// Standard deviation as a percent of the mean value. See `std_dev` and `mean`.
89 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
90 /// `median_abs_dev_pct` for unknown distributions.
91 fn std_dev_pct(self) -> f64;
93 /// Scaled median of the absolute deviations of each sample from the sample median. This is a
94 /// robust (distribution-agnostic) estimator of sample variability. Use this in preference to
95 /// `std_dev` if you cannot assume your sample is normally distributed. Note that this is scaled
96 /// by the constant `1.4826` to allow its use as a consistent estimator for the standard
99 /// See: http://en.wikipedia.org/wiki/Median_absolute_deviation
100 fn median_abs_dev(self) -> f64;
102 /// Median absolute deviation as a percent of the median. See `median_abs_dev` and `median`.
103 fn median_abs_dev_pct(self) -> f64;
105 /// Percentile: the value below which `pct` percent of the values in `self` fall. For example,
106 /// percentile(95.0) will return the value `v` such that 95% of the samples `s` in `self`
107 /// satisfy `s <= v`.
109 /// Calculated by linear interpolation between closest ranks.
111 /// See: http://en.wikipedia.org/wiki/Percentile
112 fn percentile(self, pct: f64) -> f64;
114 /// Quartiles of the sample: three values that divide the sample into four equal groups, each
115 /// with 1/4 of the data. The middle value is the median. See `median` and `percentile`. This
116 /// function may calculate the 3 quartiles more efficiently than 3 calls to `percentile`, but
117 /// is otherwise equivalent.
119 /// See also: https://en.wikipedia.org/wiki/Quartile
120 fn quartiles(self) -> (f64,f64,f64);
122 /// Inter-quartile range: the difference between the 25th percentile (1st quartile) and the 75th
123 /// percentile (3rd quartile). See `quartiles`.
125 /// See also: https://en.wikipedia.org/wiki/Interquartile_range
129 /// Extracted collection of all the summary statistics of a sample set.
130 #[deriving(Clone, Eq)]
131 #[allow(missing_doc)]
140 pub std_dev_pct: f64,
141 pub median_abs_dev: f64,
142 pub median_abs_dev_pct: f64,
143 pub quartiles: (f64,f64,f64),
149 /// Construct a new summary of a sample set.
150 pub fn new(samples: &[f64]) -> Summary {
155 mean: samples.mean(),
156 median: samples.median(),
158 std_dev: samples.std_dev(),
159 std_dev_pct: samples.std_dev_pct(),
160 median_abs_dev: samples.median_abs_dev(),
161 median_abs_dev_pct: samples.median_abs_dev_pct(),
162 quartiles: samples.quartiles(),
168 impl<'a> Stats for &'a [f64] {
170 // FIXME #11059 handle NaN, inf and overflow
171 #[allow(deprecated_owned_vector)]
172 fn sum(self) -> f64 {
173 let mut partials = vec![];
175 for &mut x in self.iter() {
177 // This inner loop applies `hi`/`lo` summation to each
178 // partial so that the list of partial sums remains exact.
179 for i in range(0, partials.len()) {
180 let mut y = *partials.get(i);
181 if num::abs(x) < num::abs(y) {
182 mem::swap(&mut x, &mut y);
184 // Rounded `x+y` is stored in `hi` with round-off stored in
185 // `lo`. Together `hi+lo` are exactly equal to `x+y`.
187 let lo = y - (hi - x);
189 *partials.get_mut(j) = lo;
194 if j >= partials.len() {
197 *partials.get_mut(j) = x;
198 partials.truncate(j+1);
201 partials.iter().fold(0.0, |p, q| p + *q)
204 fn min(self) -> f64 {
205 assert!(self.len() != 0);
206 self.iter().fold(self[0], |p, q| p.min(*q))
209 fn max(self) -> f64 {
210 assert!(self.len() != 0);
211 self.iter().fold(self[0], |p, q| p.max(*q))
214 fn mean(self) -> f64 {
215 assert!(self.len() != 0);
216 self.sum() / (self.len() as f64)
219 fn median(self) -> f64 {
220 self.percentile(50.0)
223 fn var(self) -> f64 {
227 let mean = self.mean();
229 for s in self.iter() {
233 // NB: this is _supposed to be_ len-1, not len. If you
234 // change it back to len, you will be calculating a
235 // population variance, not a sample variance.
236 v/((self.len()-1) as f64)
240 fn std_dev(self) -> f64 {
244 fn std_dev_pct(self) -> f64 {
245 (self.std_dev() / self.mean()) * 100.0
248 fn median_abs_dev(self) -> f64 {
249 let med = self.median();
250 let abs_devs: Vec<f64> = self.iter().map(|&v| num::abs(med - v)).collect();
251 // This constant is derived by smarter statistics brains than me, but it is
252 // consistent with how R and other packages treat the MAD.
253 abs_devs.as_slice().median() * 1.4826
256 fn median_abs_dev_pct(self) -> f64 {
257 (self.median_abs_dev() / self.median()) * 100.0
260 fn percentile(self, pct: f64) -> f64 {
261 let mut tmp = Vec::from_slice(self);
262 f64_sort(tmp.as_mut_slice());
263 percentile_of_sorted(tmp.as_slice(), pct)
266 fn quartiles(self) -> (f64,f64,f64) {
267 let mut tmp = Vec::from_slice(self);
268 f64_sort(tmp.as_mut_slice());
269 let a = percentile_of_sorted(tmp.as_slice(), 25.0);
270 let b = percentile_of_sorted(tmp.as_slice(), 50.0);
271 let c = percentile_of_sorted(tmp.as_slice(), 75.0);
275 fn iqr(self) -> f64 {
276 let (a,_,c) = self.quartiles();
282 // Helper function: extract a value representing the `pct` percentile of a sorted sample-set, using
283 // linear interpolation. If samples are not sorted, return nonsensical value.
284 fn percentile_of_sorted(sorted_samples: &[f64],
286 assert!(sorted_samples.len() != 0);
287 if sorted_samples.len() == 1 {
288 return sorted_samples[0];
291 assert!(pct <= 100.0);
293 return sorted_samples[sorted_samples.len() - 1];
295 let rank = (pct / 100.0) * ((sorted_samples.len() - 1) as f64);
296 let lrank = rank.floor();
297 let d = rank - lrank;
298 let n = lrank as uint;
299 let lo = sorted_samples[n];
300 let hi = sorted_samples[n+1];
305 /// Winsorize a set of samples, replacing values above the `100-pct` percentile and below the `pct`
306 /// percentile with those percentiles themselves. This is a way of minimizing the effect of
307 /// outliers, at the cost of biasing the sample. It differs from trimming in that it does not
308 /// change the number of samples, just changes the values of those that are outliers.
310 /// See: http://en.wikipedia.org/wiki/Winsorising
311 pub fn winsorize(samples: &mut [f64], pct: f64) {
312 let mut tmp = Vec::from_slice(samples);
313 f64_sort(tmp.as_mut_slice());
314 let lo = percentile_of_sorted(tmp.as_slice(), pct);
315 let hi = percentile_of_sorted(tmp.as_slice(), 100.0-pct);
316 for samp in samples.mut_iter() {
319 } else if *samp < lo {
325 /// Render writes the min, max and quartiles of the provided `Summary` to the provided `Writer`.
326 pub fn write_5_number_summary(w: &mut io::Writer,
327 s: &Summary) -> io::IoResult<()> {
328 let (q1,q2,q3) = s.quartiles;
329 write!(w, "(min={}, q1={}, med={}, q3={}, max={})",
337 /// Render a boxplot to the provided writer. The boxplot shows the min, max and quartiles of the
338 /// provided `Summary` (thus includes the mean) and is scaled to display within the range of the
339 /// nearest multiple-of-a-power-of-ten above and below the min and max of possible values, and
340 /// target `width_hint` characters of display (though it will be wider if necessary).
342 /// As an example, the summary with 5-number-summary `(min=15, q1=17, med=20, q3=24, max=31)` might
346 /// 10 | [--****#******----------] | 40
349 pub fn write_boxplot(w: &mut io::Writer, s: &Summary,
350 width_hint: uint) -> io::IoResult<()> {
352 let (q1,q2,q3) = s.quartiles;
354 // the .abs() handles the case where numbers are negative
355 let lomag = (10.0_f64).powf(&(s.min.abs().log10().floor()));
356 let himag = (10.0_f64).powf(&(s.max.abs().log10().floor()));
358 // need to consider when the limit is zero
359 let lo = if lomag == 0.0 {
362 (s.min / lomag).floor() * lomag
365 let hi = if himag == 0.0 {
368 (s.max / himag).ceil() * himag
373 let lostr = lo.to_str();
374 let histr = hi.to_str();
376 let overhead_width = lostr.len() + histr.len() + 4;
377 let range_width = width_hint - overhead_width;;
378 let char_step = range / (range_width as f64);
380 try!(write!(w, "{} |", lostr));
385 while c < range_width && v < s.min {
386 try!(write!(w, " "));
390 try!(write!(w, "["));
392 while c < range_width && v < q1 {
393 try!(write!(w, "-"));
397 while c < range_width && v < q2 {
398 try!(write!(w, "*"));
402 try!(write!(w, r"\#"));
404 while c < range_width && v < q3 {
405 try!(write!(w, "*"));
409 while c < range_width && v < s.max {
410 try!(write!(w, "-"));
414 try!(write!(w, "]"));
415 while c < range_width {
416 try!(write!(w, " "));
421 try!(write!(w, "| {}", histr));
425 /// Returns a HashMap with the number of occurrences of every element in the
426 /// sequence that the iterator exposes.
427 pub fn freq_count<T: Iterator<U>, U: TotalEq+Hash>(mut iter: T) -> hashmap::HashMap<U, uint> {
428 let mut map: hashmap::HashMap<U,uint> = hashmap::HashMap::new();
430 map.insert_or_update_with(elem, 1, |_, count| *count += 1);
435 // Test vectors generated from R, using the script src/etc/stat-test-vectors.r.
441 use stats::write_5_number_summary;
442 use stats::write_boxplot;
447 macro_rules! assert_approx_eq(
448 ($a:expr, $b:expr) => ({
449 let (a, b) = (&$a, &$b);
450 assert!((*a - *b).abs() < 1.0e-6,
451 "{} is not approximately equal to {}", *a, *b);
455 fn check(samples: &[f64], summ: &Summary) {
457 let summ2 = Summary::new(samples);
459 let mut w = io::stdout();
460 let w = &mut w as &mut io::Writer;
461 (write!(w, "\n")).unwrap();
462 write_5_number_summary(w, &summ2).unwrap();
463 (write!(w, "\n")).unwrap();
464 write_boxplot(w, &summ2, 50).unwrap();
465 (write!(w, "\n")).unwrap();
467 assert_eq!(summ.sum, summ2.sum);
468 assert_eq!(summ.min, summ2.min);
469 assert_eq!(summ.max, summ2.max);
470 assert_eq!(summ.mean, summ2.mean);
471 assert_eq!(summ.median, summ2.median);
473 // We needed a few more digits to get exact equality on these
474 // but they're within float epsilon, which is 1.0e-6.
475 assert_approx_eq!(summ.var, summ2.var);
476 assert_approx_eq!(summ.std_dev, summ2.std_dev);
477 assert_approx_eq!(summ.std_dev_pct, summ2.std_dev_pct);
478 assert_approx_eq!(summ.median_abs_dev, summ2.median_abs_dev);
479 assert_approx_eq!(summ.median_abs_dev_pct, summ2.median_abs_dev_pct);
481 assert_eq!(summ.quartiles, summ2.quartiles);
482 assert_eq!(summ.iqr, summ2.iqr);
486 fn test_min_max_nan() {
487 let xs = &[1.0, 2.0, f64::NAN, 3.0, 4.0];
488 let summary = Summary::new(xs);
489 assert_eq!(summary.min, 1.0);
490 assert_eq!(summary.max, 4.0);
499 let summ = &Summary {
500 sum: 1882.0000000000,
503 mean: 941.0000000000,
504 median: 941.0000000000,
506 std_dev: 24.0416305603,
507 std_dev_pct: 2.5549022912,
508 median_abs_dev: 25.2042000000,
509 median_abs_dev_pct: 2.6784484591,
510 quartiles: (932.5000000000,941.0000000000,949.5000000000),
516 fn test_norm10narrow() {
529 let summ = &Summary {
530 sum: 9996.0000000000,
532 max: 1217.0000000000,
533 mean: 999.6000000000,
534 median: 970.5000000000,
535 var: 16050.7111111111,
536 std_dev: 126.6914010938,
537 std_dev_pct: 12.6742097933,
538 median_abs_dev: 102.2994000000,
539 median_abs_dev_pct: 10.5408964451,
540 quartiles: (956.7500000000,970.5000000000,1078.7500000000),
546 fn test_norm10medium() {
559 let summ = &Summary {
560 sum: 8653.0000000000,
562 max: 1084.0000000000,
563 mean: 865.3000000000,
564 median: 911.5000000000,
565 var: 48628.4555555556,
566 std_dev: 220.5186059170,
567 std_dev_pct: 25.4846418487,
568 median_abs_dev: 195.7032000000,
569 median_abs_dev_pct: 21.4704552935,
570 quartiles: (771.0000000000,911.5000000000,1017.2500000000),
576 fn test_norm10wide() {
589 let summ = &Summary {
590 sum: 9349.0000000000,
592 max: 1591.0000000000,
593 mean: 934.9000000000,
594 median: 913.5000000000,
595 var: 239208.9888888889,
596 std_dev: 489.0899599142,
597 std_dev_pct: 52.3146817750,
598 median_abs_dev: 611.5725000000,
599 median_abs_dev_pct: 66.9482758621,
600 quartiles: (567.2500000000,913.5000000000,1331.2500000000),
606 fn test_norm25verynarrow() {
634 let summ = &Summary {
635 sum: 24926.0000000000,
637 max: 1040.0000000000,
638 mean: 997.0400000000,
639 median: 998.0000000000,
641 std_dev: 19.8294393937,
642 std_dev_pct: 1.9888308788,
643 median_abs_dev: 22.2390000000,
644 median_abs_dev_pct: 2.2283567134,
645 quartiles: (983.0000000000,998.0000000000,1013.0000000000),
664 let summ = &Summary {
669 median: 11.5000000000,
671 std_dev: 16.9643416875,
672 std_dev_pct: 101.5828843560,
673 median_abs_dev: 13.3434000000,
674 median_abs_dev_pct: 116.0295652174,
675 quartiles: (4.2500000000,11.5000000000,22.5000000000),
694 let summ = &Summary {
699 median: 24.5000000000,
701 std_dev: 19.5848580967,
702 std_dev_pct: 74.4671410520,
703 median_abs_dev: 22.9803000000,
704 median_abs_dev_pct: 93.7971428571,
705 quartiles: (9.5000000000,24.5000000000,36.5000000000),
724 let summ = &Summary {
729 median: 22.0000000000,
731 std_dev: 21.4050876611,
732 std_dev_pct: 88.4507754589,
733 median_abs_dev: 21.4977000000,
734 median_abs_dev_pct: 97.7168181818,
735 quartiles: (7.7500000000,22.0000000000,35.0000000000),
769 let summ = &Summary {
774 median: 19.0000000000,
776 std_dev: 24.5161851301,
777 std_dev_pct: 103.3565983562,
778 median_abs_dev: 19.2738000000,
779 median_abs_dev_pct: 101.4410526316,
780 quartiles: (6.0000000000,19.0000000000,31.0000000000),
814 let summ = &Summary {
819 median: 20.0000000000,
821 std_dev: 4.5650848842,
822 std_dev_pct: 22.2037202539,
823 median_abs_dev: 5.9304000000,
824 median_abs_dev_pct: 29.6520000000,
825 quartiles: (17.0000000000,20.0000000000,24.0000000000),
831 fn test_pois25lambda30() {
859 let summ = &Summary {
864 median: 32.0000000000,
866 std_dev: 5.1568724372,
867 std_dev_pct: 16.3814245145,
868 median_abs_dev: 5.9304000000,
869 median_abs_dev_pct: 18.5325000000,
870 quartiles: (28.0000000000,32.0000000000,34.0000000000),
876 fn test_pois25lambda40() {
904 let summ = &Summary {
905 sum: 1019.0000000000,
909 median: 42.0000000000,
911 std_dev: 5.8685603004,
912 std_dev_pct: 14.3978417577,
913 median_abs_dev: 5.9304000000,
914 median_abs_dev_pct: 14.1200000000,
915 quartiles: (37.0000000000,42.0000000000,45.0000000000),
921 fn test_pois25lambda50() {
949 let summ = &Summary {
950 sum: 1235.0000000000,
954 median: 50.0000000000,
956 std_dev: 5.6273143387,
957 std_dev_pct: 11.3913245723,
958 median_abs_dev: 4.4478000000,
959 median_abs_dev_pct: 8.8956000000,
960 quartiles: (44.0000000000,50.0000000000,52.0000000000),
994 let summ = &Summary {
995 sum: 1242.0000000000,
999 median: 45.0000000000,
1000 var: 1015.6433333333,
1001 std_dev: 31.8691595957,
1002 std_dev_pct: 64.1488719719,
1003 median_abs_dev: 45.9606000000,
1004 median_abs_dev_pct: 102.1346666667,
1005 quartiles: (29.0000000000,45.0000000000,79.0000000000),
1012 fn test_boxplot_nonpositive() {
1013 #[allow(deprecated_owned_vector)]
1014 fn t(s: &Summary, expected: ~str) {
1015 use std::io::MemWriter;
1016 let mut m = MemWriter::new();
1017 write_boxplot(&mut m as &mut io::Writer, s, 30).unwrap();
1018 let out = str::from_utf8(m.unwrap().as_slice()).unwrap().to_owned();
1019 assert_eq!(out, expected);
1022 t(&Summary::new([-2.0, -1.0]), ~"-2 |[------******#*****---]| -1");
1023 t(&Summary::new([0.0, 2.0]), ~"0 |[-------*****#*******---]| 2");
1024 t(&Summary::new([-2.0, 0.0]), ~"-2 |[------******#******---]| 0");
1028 fn test_sum_f64s() {
1029 assert_eq!([0.5, 3.2321, 1.5678].sum(), 5.2999);
1032 fn test_sum_f64_between_ints_that_sum_to_0() {
1033 assert_eq!([1e30, 1.2, -1e30].sum(), 1.2);
1043 pub fn sum_three_items(b: &mut Bencher) {
1045 [1e20, 1.5, -1e20].sum();
1049 pub fn sum_many_f64(b: &mut Bencher) {
1050 let nums = [-1e30, 1e60, 1e30, 1.0, -1e60];
1051 let v = Vec::from_fn(500, |i| nums[i%5]);