criterion/stats/univariate/
percentiles.rs

1use cast::{self, usize};
2
3use crate::stats::float::Float;
4
5/// A "view" into the percentiles of a sample
6pub struct Percentiles<A>(Box<[A]>)
7where
8    A: Float;
9
10// TODO(rust-lang/rfcs#735) move this `impl` into a private percentiles module
11impl<A> Percentiles<A>
12where
13    A: Float,
14    usize: cast::From<A, Output = Result<usize, cast::Error>>,
15{
16    /// Returns the percentile at `p`%
17    ///
18    /// Safety:
19    ///
20    /// - Make sure that `p` is in the range `[0, 100]`
21    unsafe fn at_unchecked(&self, p: A) -> A {
22        unsafe {
23            let _100 = A::cast(100);
24            debug_assert!(p >= A::cast(0) && p <= _100);
25            debug_assert!(self.0.len() > 0);
26            let len = self.0.len() - 1;
27
28            if p == _100 {
29                self.0[len]
30            } else {
31                let rank = (p / _100) * A::cast(len);
32                let integer = rank.floor();
33                let fraction = rank - integer;
34                let n = usize(integer).unwrap();
35                let &floor = self.0.get_unchecked(n);
36                let &ceiling = self.0.get_unchecked(n + 1);
37
38                floor + (ceiling - floor) * fraction
39            }
40        }
41    }
42
43    /// Returns the percentile at `p`%
44    ///
45    /// # Panics
46    ///
47    /// Panics if `p` is outside the closed `[0, 100]` range
48    pub fn at(&self, p: A) -> A {
49        let _0 = A::cast(0);
50        let _100 = A::cast(100);
51
52        assert!(p >= _0 && p <= _100);
53        assert!(self.0.len() > 0);
54
55        unsafe { self.at_unchecked(p) }
56    }
57
58    /// Returns the interquartile range
59    pub fn iqr(&self) -> A {
60        let q1 = self.at(A::cast(25));
61        let q3 = self.at(A::cast(75));
62
63        q3 - q1
64    }
65
66    /// Returns the 50th percentile
67    pub fn median(&self) -> A {
68        self.at(A::cast(50))
69    }
70
71    /// Returns the 25th, 50th and 75th percentiles
72    pub fn quartiles(&self) -> (A, A, A) {
73        (self.at(A::cast(25)), self.at(A::cast(50)), self.at(A::cast(75)))
74    }
75}