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.
16 // NB: this can probably be rewritten in terms of num::Num
17 // to be less f64-specific.
19 /// Trait that provides simple descriptive statistics on a univariate set of numeric samples.
22 /// Sum of the samples.
25 /// Minimum value of the samples.
28 /// Maximum value of the samples.
31 /// Arithmetic mean (average) of the samples: sum divided by sample-count.
33 /// See: https://en.wikipedia.org/wiki/Arithmetic_mean
36 /// Median of the samples: value separating the lower half of the samples from the higher half.
37 /// Equal to `self.percentile(50.0)`.
39 /// See: https://en.wikipedia.org/wiki/Median
40 fn median(self) -> f64;
42 /// Variance of the samples: bias-corrected mean of the squares of the differences of each
43 /// sample from the sample mean. Note that this calculates the _sample variance_ rather than the
44 /// population variance, which is assumed to be unknown. It therefore corrects the `(n-1)/n`
45 /// bias that would appear if we calculated a population variance, by dividing by `(n-1)` rather
48 /// See: https://en.wikipedia.org/wiki/Variance
51 /// Standard deviation: the square root of the sample variance.
53 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
54 /// `median_abs_dev` for unknown distributions.
56 /// See: https://en.wikipedia.org/wiki/Standard_deviation
57 fn std_dev(self) -> f64;
59 /// Standard deviation as a percent of the mean value. See `std_dev` and `mean`.
61 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
62 /// `median_abs_dev_pct` for unknown distributions.
63 fn std_dev_pct(self) -> f64;
65 /// Scaled median of the absolute deviations of each sample from the sample median. This is a
66 /// robust (distribution-agnostic) estimator of sample variability. Use this in preference to
67 /// `std_dev` if you cannot assume your sample is normally distributed. Note that this is scaled
68 /// by the constant `1.4826` to allow its use as a consistent estimator for the standard
71 /// See: http://en.wikipedia.org/wiki/Median_absolute_deviation
72 fn median_abs_dev(self) -> f64;
74 /// Median absolute deviation as a percent of the median. See `median_abs_dev` and `median`.
75 fn median_abs_dev_pct(self) -> f64;
77 /// Percentile: the value below which `pct` percent of the values in `self` fall. For example,
78 /// percentile(95.0) will return the value `v` such that that 95% of the samples `s` in `self`
81 /// Calculated by linear interpolation between closest ranks.
83 /// See: http://en.wikipedia.org/wiki/Percentile
84 fn percentile(self, pct: f64) -> f64;
86 /// Quartiles of the sample: three values that divide the sample into four equal groups, each
87 /// with 1/4 of the data. The middle value is the median. See `median` and `percentile`. This
88 /// function may calculate the 3 quartiles more efficiently than 3 calls to `percentile`, but
89 /// is otherwise equivalent.
91 /// See also: https://en.wikipedia.org/wiki/Quartile
92 fn quartiles(self) -> (f64,f64,f64);
94 /// Inter-quartile range: the difference between the 25th percentile (1st quartile) and the 75th
95 /// percentile (3rd quartile). See `quartiles`.
97 /// See also: https://en.wikipedia.org/wiki/Interquartile_range
101 /// Extracted collection of all the summary statistics of a sample set.
102 #[deriving(Clone, Eq)]
113 median_abs_dev_pct: f64,
114 quartiles: (f64,f64,f64),
120 /// Construct a new summary of a sample set.
121 pub fn new(samples: &[f64]) -> Summary {
126 mean: samples.mean(),
127 median: samples.median(),
129 std_dev: samples.std_dev(),
130 std_dev_pct: samples.std_dev_pct(),
131 median_abs_dev: samples.median_abs_dev(),
132 median_abs_dev_pct: samples.median_abs_dev_pct(),
133 quartiles: samples.quartiles(),
139 impl<'self> Stats for &'self [f64] {
141 fn sum(self) -> f64 {
142 self.iter().fold(0.0, |p,q| p + *q)
145 fn min(self) -> f64 {
146 assert!(self.len() != 0);
147 self.iter().fold(self[0], |p,q| cmp::min(p, *q))
150 fn max(self) -> f64 {
151 assert!(self.len() != 0);
152 self.iter().fold(self[0], |p,q| cmp::max(p, *q))
155 fn mean(self) -> f64 {
156 assert!(self.len() != 0);
157 self.sum() / (self.len() as f64)
160 fn median(self) -> f64 {
161 self.percentile(50.0)
164 fn var(self) -> f64 {
168 let mean = self.mean();
170 for s in self.iter() {
174 // NB: this is _supposed to be_ len-1, not len. If you
175 // change it back to len, you will be calculating a
176 // population variance, not a sample variance.
177 v/((self.len()-1) as f64)
181 fn std_dev(self) -> f64 {
185 fn std_dev_pct(self) -> f64 {
186 (self.std_dev() / self.mean()) * 100.0
189 fn median_abs_dev(self) -> f64 {
190 let med = self.median();
191 let abs_devs = self.map(|&v| num::abs(med - v));
192 // This constant is derived by smarter statistics brains than me, but it is
193 // consistent with how R and other packages treat the MAD.
194 abs_devs.median() * 1.4826
197 fn median_abs_dev_pct(self) -> f64 {
198 (self.median_abs_dev() / self.median()) * 100.0
201 fn percentile(self, pct: f64) -> f64 {
202 let mut tmp = self.to_owned();
204 percentile_of_sorted(tmp, pct)
207 fn quartiles(self) -> (f64,f64,f64) {
208 let mut tmp = self.to_owned();
210 let a = percentile_of_sorted(tmp, 25.0);
211 let b = percentile_of_sorted(tmp, 50.0);
212 let c = percentile_of_sorted(tmp, 75.0);
216 fn iqr(self) -> f64 {
217 let (a,_,c) = self.quartiles();
223 // Helper function: extract a value representing the `pct` percentile of a sorted sample-set, using
224 // linear interpolation. If samples are not sorted, return nonsensical value.
225 priv fn percentile_of_sorted(sorted_samples: &[f64],
227 assert!(sorted_samples.len() != 0);
228 if sorted_samples.len() == 1 {
229 return sorted_samples[0];
232 assert!(pct <= 100.0);
234 return sorted_samples[sorted_samples.len() - 1];
236 let rank = (pct / 100.0) * ((sorted_samples.len() - 1) as f64);
237 let lrank = rank.floor();
238 let d = rank - lrank;
239 let n = lrank as uint;
240 let lo = sorted_samples[n];
241 let hi = sorted_samples[n+1];
246 /// Winsorize a set of samples, replacing values above the `100-pct` percentile and below the `pct`
247 /// percentile with those percentiles themselves. This is a way of minimizing the effect of
248 /// outliers, at the cost of biasing the sample. It differs from trimming in that it does not
249 /// change the number of samples, just changes the values of those that are outliers.
251 /// See: http://en.wikipedia.org/wiki/Winsorising
252 pub fn winsorize(samples: &mut [f64], pct: f64) {
253 let mut tmp = samples.to_owned();
255 let lo = percentile_of_sorted(tmp, pct);
256 let hi = percentile_of_sorted(tmp, 100.0-pct);
257 for samp in samples.mut_iter() {
260 } else if *samp < lo {
266 /// Render writes the min, max and quartiles of the provided `Summary` to the provided `Writer`.
267 pub fn write_5_number_summary(w: @io::Writer, s: &Summary) {
268 let (q1,q2,q3) = s.quartiles;
269 w.write_str(fmt!("(min=%f, q1=%f, med=%f, q3=%f, max=%f)",
277 /// Render a boxplot to the provided writer. The boxplot shows the min, max and quartiles of the
278 /// provided `Summary` (thus includes the mean) and is scaled to display within the range of the
279 /// nearest multiple-of-a-power-of-ten above and below the min and max of possible values, and
280 /// target `width_hint` characters of display (though it will be wider if necessary).
282 /// As an example, the summary with 5-number-summary `(min=15, q1=17, med=20, q3=24, max=31)` might
286 /// 10 | [--****#******----------] | 40
289 pub fn write_boxplot(w: @io::Writer, s: &Summary, width_hint: uint) {
291 let (q1,q2,q3) = s.quartiles;
293 let lomag = (10.0_f64).pow(&s.min.log10().floor());
294 let himag = (10.0_f64).pow(&(s.max.log10().floor()));
295 let lo = (s.min / lomag).floor() * lomag;
296 let hi = (s.max / himag).ceil() * himag;
300 let lostr = lo.to_str();
301 let histr = hi.to_str();
303 let overhead_width = lostr.len() + histr.len() + 4;
304 let range_width = width_hint - overhead_width;;
305 let char_step = range / (range_width as f64);
314 while c < range_width && v < s.min {
321 while c < range_width && v < q1 {
326 while c < range_width && v < q2 {
333 while c < range_width && v < q3 {
338 while c < range_width && v < s.max {
344 while c < range_width {
355 // Test vectors generated from R, using the script src/etc/stat-test-vectors.r.
362 use stats::write_5_number_summary;
363 use stats::write_boxplot;
366 fn check(samples: &[f64], summ: &Summary) {
368 let summ2 = Summary::new(samples);
370 let w = io::stdout();
372 write_5_number_summary(w, &summ2);
374 write_boxplot(w, &summ2, 50);
377 assert_eq!(summ.sum, summ2.sum);
378 assert_eq!(summ.min, summ2.min);
379 assert_eq!(summ.max, summ2.max);
380 assert_eq!(summ.mean, summ2.mean);
381 assert_eq!(summ.median, summ2.median);
383 // We needed a few more digits to get exact equality on these
384 // but they're within float epsilon, which is 1.0e-6.
385 assert_approx_eq!(summ.var, summ2.var);
386 assert_approx_eq!(summ.std_dev, summ2.std_dev);
387 assert_approx_eq!(summ.std_dev_pct, summ2.std_dev_pct);
388 assert_approx_eq!(summ.median_abs_dev, summ2.median_abs_dev);
389 assert_approx_eq!(summ.median_abs_dev_pct, summ2.median_abs_dev_pct);
391 assert_eq!(summ.quartiles, summ2.quartiles);
392 assert_eq!(summ.iqr, summ2.iqr);
401 let summ = &Summary {
402 sum: 1882.0000000000,
405 mean: 941.0000000000,
406 median: 941.0000000000,
408 std_dev: 24.0416305603,
409 std_dev_pct: 2.5549022912,
410 median_abs_dev: 25.2042000000,
411 median_abs_dev_pct: 2.6784484591,
412 quartiles: (932.5000000000,941.0000000000,949.5000000000),
418 fn test_norm10narrow() {
431 let summ = &Summary {
432 sum: 9996.0000000000,
434 max: 1217.0000000000,
435 mean: 999.6000000000,
436 median: 970.5000000000,
437 var: 16050.7111111111,
438 std_dev: 126.6914010938,
439 std_dev_pct: 12.6742097933,
440 median_abs_dev: 102.2994000000,
441 median_abs_dev_pct: 10.5408964451,
442 quartiles: (956.7500000000,970.5000000000,1078.7500000000),
448 fn test_norm10medium() {
461 let summ = &Summary {
462 sum: 8653.0000000000,
464 max: 1084.0000000000,
465 mean: 865.3000000000,
466 median: 911.5000000000,
467 var: 48628.4555555556,
468 std_dev: 220.5186059170,
469 std_dev_pct: 25.4846418487,
470 median_abs_dev: 195.7032000000,
471 median_abs_dev_pct: 21.4704552935,
472 quartiles: (771.0000000000,911.5000000000,1017.2500000000),
478 fn test_norm10wide() {
491 let summ = &Summary {
492 sum: 9349.0000000000,
494 max: 1591.0000000000,
495 mean: 934.9000000000,
496 median: 913.5000000000,
497 var: 239208.9888888889,
498 std_dev: 489.0899599142,
499 std_dev_pct: 52.3146817750,
500 median_abs_dev: 611.5725000000,
501 median_abs_dev_pct: 66.9482758621,
502 quartiles: (567.2500000000,913.5000000000,1331.2500000000),
508 fn test_norm25verynarrow() {
536 let summ = &Summary {
537 sum: 24926.0000000000,
539 max: 1040.0000000000,
540 mean: 997.0400000000,
541 median: 998.0000000000,
543 std_dev: 19.8294393937,
544 std_dev_pct: 1.9888308788,
545 median_abs_dev: 22.2390000000,
546 median_abs_dev_pct: 2.2283567134,
547 quartiles: (983.0000000000,998.0000000000,1013.0000000000),
566 let summ = &Summary {
571 median: 11.5000000000,
573 std_dev: 16.9643416875,
574 std_dev_pct: 101.5828843560,
575 median_abs_dev: 13.3434000000,
576 median_abs_dev_pct: 116.0295652174,
577 quartiles: (4.2500000000,11.5000000000,22.5000000000),
596 let summ = &Summary {
601 median: 24.5000000000,
603 std_dev: 19.5848580967,
604 std_dev_pct: 74.4671410520,
605 median_abs_dev: 22.9803000000,
606 median_abs_dev_pct: 93.7971428571,
607 quartiles: (9.5000000000,24.5000000000,36.5000000000),
626 let summ = &Summary {
631 median: 22.0000000000,
633 std_dev: 21.4050876611,
634 std_dev_pct: 88.4507754589,
635 median_abs_dev: 21.4977000000,
636 median_abs_dev_pct: 97.7168181818,
637 quartiles: (7.7500000000,22.0000000000,35.0000000000),
671 let summ = &Summary {
676 median: 19.0000000000,
678 std_dev: 24.5161851301,
679 std_dev_pct: 103.3565983562,
680 median_abs_dev: 19.2738000000,
681 median_abs_dev_pct: 101.4410526316,
682 quartiles: (6.0000000000,19.0000000000,31.0000000000),
716 let summ = &Summary {
721 median: 20.0000000000,
723 std_dev: 4.5650848842,
724 std_dev_pct: 22.2037202539,
725 median_abs_dev: 5.9304000000,
726 median_abs_dev_pct: 29.6520000000,
727 quartiles: (17.0000000000,20.0000000000,24.0000000000),
733 fn test_pois25lambda30() {
761 let summ = &Summary {
766 median: 32.0000000000,
768 std_dev: 5.1568724372,
769 std_dev_pct: 16.3814245145,
770 median_abs_dev: 5.9304000000,
771 median_abs_dev_pct: 18.5325000000,
772 quartiles: (28.0000000000,32.0000000000,34.0000000000),
778 fn test_pois25lambda40() {
806 let summ = &Summary {
807 sum: 1019.0000000000,
811 median: 42.0000000000,
813 std_dev: 5.8685603004,
814 std_dev_pct: 14.3978417577,
815 median_abs_dev: 5.9304000000,
816 median_abs_dev_pct: 14.1200000000,
817 quartiles: (37.0000000000,42.0000000000,45.0000000000),
823 fn test_pois25lambda50() {
851 let summ = &Summary {
852 sum: 1235.0000000000,
856 median: 50.0000000000,
858 std_dev: 5.6273143387,
859 std_dev_pct: 11.3913245723,
860 median_abs_dev: 4.4478000000,
861 median_abs_dev_pct: 8.8956000000,
862 quartiles: (44.0000000000,50.0000000000,52.0000000000),
896 let summ = &Summary {
897 sum: 1242.0000000000,
901 median: 45.0000000000,
902 var: 1015.6433333333,
903 std_dev: 31.8691595957,
904 std_dev_pct: 64.1488719719,
905 median_abs_dev: 45.9606000000,
906 median_abs_dev_pct: 102.1346666667,
907 quartiles: (29.0000000000,45.0000000000,79.0000000000),