interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / measure / stats.rs

48 lines · 1863 bytes Raw Blame History
1//! The one percentile function used for both the median and the empirical p95.
2
3/// Rejects empty input and any non-finite or negative value. Never clamps.
4pub fn validate_samples(values: &[f64]) -> Result<(), String> {
5 if values.is_empty() {
6 return Err("no samples".to_string());
7 }
8 for (i, v) in values.iter().enumerate() {
9 if !v.is_finite() {
10 return Err(format!("sample {i} is not finite: {v}"));
11 }
12 if *v < 0.0 {
13 return Err(format!("sample {i} is negative: {v}"));
14 }
15 }
16 Ok(())
17}
18
19/// Nearest-rank percentile on the ascending sorted values:
20/// `index = ceil(p / 100 * n) - 1`, clamped to `0..n`. `p` is in percent, `0.0..=100.0`.
21/// The product `p * n` is formed before dividing by 100 so whole-number percentiles hit exact
22/// integers (95 * 20 / 100 = 19, never 19.000000000000004).
23pub fn percentile_nearest_rank(values: &[f64], p: f64) -> Result<f64, String> {
24 validate_samples(values)?;
25 if !p.is_finite() || !(0.0..=100.0).contains(&p) {
26 return Err(format!("percentile must be within 0..=100, got {p}"));
27 }
28 let mut sorted = values.to_vec();
29 sorted.sort_by(|a, b| a.total_cmp(b));
30 let n = sorted.len();
31 let rank = (p * n as f64 / 100.0).ceil() as i64 - 1;
32 let index = rank.clamp(0, n as i64 - 1) as usize;
33 Ok(sorted[index])
34}
35
36/// The ranking input. Reported under its own name, `latency_median_us`.
37pub fn median(values: &[f64]) -> Result<f64, String> {
38 percentile_nearest_rank(values, 50.0)
39}
40
41/// Empirical p95, or `Ok(None)` (unavailable) below `min_samples` valid samples.
42pub fn p95_if_sufficient(values: &[f64], min_samples: usize) -> Result<Option<f64>, String> {
43 validate_samples(values)?;
44 if values.len() < min_samples {
45 return Ok(None);
46 }
47 percentile_nearest_rank(values, 95.0).map(Some)
48}