Calculate quantile with linear interpolation. This is intended to match pytest-codspeed's computation, which uses python's statistics.quantiles `p` is the quantile (e.g., 0.25 for Q1, 0.75 for Q3).
(sorted_data: &[f64], p: f64)
| 127 | /// |
| 128 | /// `p` is the quantile (e.g., 0.25 for Q1, 0.75 for Q3). |
| 129 | fn quantile(sorted_data: &[f64], p: f64) -> f64 { |
| 130 | let n = sorted_data.len(); |
| 131 | if n == 0 { |
| 132 | return 0.0; |
| 133 | } |
| 134 | if n == 1 { |
| 135 | return sorted_data[0]; |
| 136 | } |
| 137 | if n == 2 { |
| 138 | // Linear interpolation between the two values |
| 139 | return sorted_data[0] * (1.0 - p) + sorted_data[1] * p; |
| 140 | } |
| 141 | |
| 142 | // Python's exclusive method: position = p * (n + 1) - 1 (0-based indexing) |
| 143 | let pos = p * (n as f64 + 1.0) - 1.0; |
| 144 | let idx = pos.floor() as usize; |
| 145 | let frac = pos - pos.floor(); |
| 146 | |
| 147 | if idx + 1 < n { |
| 148 | sorted_data[idx] * (1.0 - frac) + sorted_data[idx + 1] * frac |
| 149 | } else { |
| 150 | sorted_data[idx.min(n - 1)] |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | #[cfg(test)] |
| 155 | mod tests { |