]>
git.proxmox.com Git - rustc.git/blob - library/test/src/stats.rs
1 #![allow(missing_docs)]
8 fn local_sort(v
: &mut [f64]) {
9 v
.sort_by(|x
: &f64, y
: &f64| x
.total_cmp(y
));
12 /// Trait that provides simple descriptive statistics on a univariate set of numeric samples.
14 /// Sum of the samples.
16 /// Note: this method sacrifices performance at the altar of accuracy
17 /// Depends on IEEE 754 arithmetic guarantees. See proof of correctness at:
18 /// ["Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric
19 /// Predicates"][paper]
21 /// [paper]: https://www.cs.cmu.edu/~quake-papers/robust-arithmetic.ps
24 /// Minimum value of the samples.
27 /// Maximum value of the samples.
30 /// Arithmetic mean (average) of the samples: sum divided by sample-count.
32 /// See: <https://en.wikipedia.org/wiki/Arithmetic_mean>
33 fn mean(&self) -> f64;
35 /// Median of the samples: value separating the lower half of the samples from the higher half.
36 /// Equal to `self.percentile(50.0)`.
38 /// See: <https://en.wikipedia.org/wiki/Median>
39 fn median(&self) -> f64;
41 /// Variance of the samples: bias-corrected mean of the squares of the differences of each
42 /// sample from the sample mean. Note that this calculates the _sample variance_ rather than the
43 /// population variance, which is assumed to be unknown. It therefore corrects the `(n-1)/n`
44 /// bias that would appear if we calculated a population variance, by dividing by `(n-1)` rather
47 /// See: <https://en.wikipedia.org/wiki/Variance>
50 /// Standard deviation: the square root of the sample variance.
52 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
53 /// `median_abs_dev` for unknown distributions.
55 /// See: <https://en.wikipedia.org/wiki/Standard_deviation>
56 fn std_dev(&self) -> f64;
58 /// Standard deviation as a percent of the mean value. See `std_dev` and `mean`.
60 /// Note: this is not a robust statistic for non-normal distributions. Prefer the
61 /// `median_abs_dev_pct` for unknown distributions.
62 fn std_dev_pct(&self) -> f64;
64 /// Scaled median of the absolute deviations of each sample from the sample median. This is a
65 /// robust (distribution-agnostic) estimator of sample variability. Use this in preference to
66 /// `std_dev` if you cannot assume your sample is normally distributed. Note that this is scaled
67 /// by the constant `1.4826` to allow its use as a consistent estimator for the standard
70 /// See: <https://en.wikipedia.org/wiki/Median_absolute_deviation>
71 fn median_abs_dev(&self) -> f64;
73 /// Median absolute deviation as a percent of the median. See `median_abs_dev` and `median`.
74 fn median_abs_dev_pct(&self) -> f64;
76 /// Percentile: the value below which `pct` percent of the values in `self` fall. For example,
77 /// percentile(95.0) will return the value `v` such that 95% of the samples `s` in `self`
80 /// Calculated by linear interpolation between closest ranks.
82 /// See: <https://en.wikipedia.org/wiki/Percentile>
83 fn percentile(&self, pct
: f64) -> f64;
85 /// Quartiles of the sample: three values that divide the sample into four equal groups, each
86 /// with 1/4 of the data. The middle value is the median. See `median` and `percentile`. This
87 /// function may calculate the 3 quartiles more efficiently than 3 calls to `percentile`, but
88 /// is otherwise equivalent.
90 /// See also: <https://en.wikipedia.org/wiki/Quartile>
91 fn quartiles(&self) -> (f64, f64, f64);
93 /// Inter-quartile range: the difference between the 25th percentile (1st quartile) and the 75th
94 /// percentile (3rd quartile). See `quartiles`.
96 /// See also: <https://en.wikipedia.org/wiki/Interquartile_range>
100 /// Extracted collection of all the summary statistics of a sample set.
101 #[derive(Debug, Clone, PartialEq, Copy)]
102 #[allow(missing_docs)]
111 pub std_dev_pct
: f64,
112 pub median_abs_dev
: f64,
113 pub median_abs_dev_pct
: f64,
114 pub quartiles
: (f64, f64, f64),
119 /// Construct a new summary of a sample set.
120 pub fn new(samples
: &[f64]) -> Summary
{
125 mean
: samples
.mean(),
126 median
: samples
.median(),
128 std_dev
: samples
.std_dev(),
129 std_dev_pct
: samples
.std_dev_pct(),
130 median_abs_dev
: samples
.median_abs_dev(),
131 median_abs_dev_pct
: samples
.median_abs_dev_pct(),
132 quartiles
: samples
.quartiles(),
138 impl Stats
for [f64] {
139 // FIXME #11059 handle NaN, inf and overflow
140 fn sum(&self) -> f64 {
141 let mut partials
= vec
![];
146 // This inner loop applies `hi`/`lo` summation to each
147 // partial so that the list of partial sums remains exact.
148 for i
in 0..partials
.len() {
149 let mut y
: f64 = partials
[i
];
150 if x
.abs() < y
.abs() {
151 mem
::swap(&mut x
, &mut y
);
153 // Rounded `x+y` is stored in `hi` with round-off stored in
154 // `lo`. Together `hi+lo` are exactly equal to `x+y`.
156 let lo
= y
- (hi
- x
);
163 if j
>= partials
.len() {
167 partials
.truncate(j
+ 1);
171 partials
.iter().fold(zero
, |p
, q
| p
+ *q
)
174 fn min(&self) -> f64 {
175 assert
!(!self.is_empty());
176 self.iter().fold(self[0], |p
, q
| p
.min(*q
))
179 fn max(&self) -> f64 {
180 assert
!(!self.is_empty());
181 self.iter().fold(self[0], |p
, q
| p
.max(*q
))
184 fn mean(&self) -> f64 {
185 assert
!(!self.is_empty());
186 self.sum() / (self.len() as f64)
189 fn median(&self) -> f64 {
190 self.percentile(50_f64)
193 fn var(&self) -> f64 {
197 let mean
= self.mean();
198 let mut v
: f64 = 0.0;
203 // N.B., this is _supposed to be_ len-1, not len. If you
204 // change it back to len, you will be calculating a
205 // population variance, not a sample variance.
206 let denom
= (self.len() - 1) as f64;
211 fn std_dev(&self) -> f64 {
215 fn std_dev_pct(&self) -> f64 {
216 let hundred
= 100_f64;
217 (self.std_dev() / self.mean()) * hundred
220 fn median_abs_dev(&self) -> f64 {
221 let med
= self.median();
222 let abs_devs
: Vec
<f64> = self.iter().map(|&v
| (med
- v
).abs()).collect();
223 // This constant is derived by smarter statistics brains than me, but it is
224 // consistent with how R and other packages treat the MAD.
226 abs_devs
.median() * number
229 fn median_abs_dev_pct(&self) -> f64 {
230 let hundred
= 100_f64;
231 (self.median_abs_dev() / self.median()) * hundred
234 fn percentile(&self, pct
: f64) -> f64 {
235 let mut tmp
= self.to_vec();
236 local_sort(&mut tmp
);
237 percentile_of_sorted(&tmp
, pct
)
240 fn quartiles(&self) -> (f64, f64, f64) {
241 let mut tmp
= self.to_vec();
242 local_sort(&mut tmp
);
244 let a
= percentile_of_sorted(&tmp
, first
);
246 let b
= percentile_of_sorted(&tmp
, second
);
248 let c
= percentile_of_sorted(&tmp
, third
);
252 fn iqr(&self) -> f64 {
253 let (a
, _
, c
) = self.quartiles();
258 // Helper function: extract a value representing the `pct` percentile of a sorted sample-set, using
259 // linear interpolation. If samples are not sorted, return nonsensical value.
260 fn percentile_of_sorted(sorted_samples
: &[f64], pct
: f64) -> f64 {
261 assert
!(!sorted_samples
.is_empty());
262 if sorted_samples
.len() == 1 {
263 return sorted_samples
[0];
266 assert
!(zero
<= pct
);
267 let hundred
= 100_f64;
268 assert
!(pct
<= hundred
);
270 return sorted_samples
[sorted_samples
.len() - 1];
272 let length
= (sorted_samples
.len() - 1) as f64;
273 let rank
= (pct
/ hundred
) * length
;
274 let lrank
= rank
.floor();
275 let d
= rank
- lrank
;
276 let n
= lrank
as usize;
277 let lo
= sorted_samples
[n
];
278 let hi
= sorted_samples
[n
+ 1];
282 /// Winsorize a set of samples, replacing values above the `100-pct` percentile
283 /// and below the `pct` percentile with those percentiles themselves. This is a
284 /// way of minimizing the effect of outliers, at the cost of biasing the sample.
285 /// It differs from trimming in that it does not change the number of samples,
286 /// just changes the values of those that are outliers.
288 /// See: <https://en.wikipedia.org/wiki/Winsorising>
289 pub fn winsorize(samples
: &mut [f64], pct
: f64) {
290 let mut tmp
= samples
.to_vec();
291 local_sort(&mut tmp
);
292 let lo
= percentile_of_sorted(&tmp
, pct
);
293 let hundred
= 100_f64;
294 let hi
= percentile_of_sorted(&tmp
, hundred
- pct
);
295 for samp
in samples
{
298 } else if *samp
< lo
{