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.
326 use self::test
::Bencher
;
327 use crate::stats
::Stats
;
330 pub fn sum_three_items(b
: &mut Bencher
) {
332 [1e20f64
, 1.5f64, -1e20f64
].sum();
336 pub fn sum_many_f64(b
: &mut Bencher
) {
337 let nums
= [-1e30f64
, 1e60
, 1e30
, 1.0, -1e60
];
338 let v
= (0..500).map(|i
| nums
[i
% 5]).collect
::<Vec
<_
>>();
346 pub fn no_iter(_
: &mut Bencher
) {}