use rand::Rng;
pub(crate) const HUMAN_TIMING_CV_FLOOR: f64 = 0.1;
pub(crate) const CV_DRIFT_FLOOR: f64 = 0.03;
#[cfg_attr(not(feature = "human"), allow(dead_code))]
pub(crate) fn standard_normal<R: Rng + ?Sized>(rng: &mut R) -> f64 {
let u1: f64 = rng.gen::<f64>().max(1e-12);
let u2: f64 = rng.gen::<f64>();
(-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
}
#[cfg_attr(not(feature = "human"), allow(dead_code))]
pub(crate) fn coefficient_of_variation(samples: &[f64]) -> Option<f64> {
if samples.len() < 2 {
return None;
}
let n = samples.len() as f64;
let mean = samples.iter().sum::<f64>() / n;
if mean <= 0.0 {
return None;
}
let variance = samples
.iter()
.map(|x| {
let d = x - mean;
d * d
})
.sum::<f64>()
/ n;
Some(variance.sqrt() / mean)
}
#[cfg(test)]
mod tests {
use super::*;
use rand::{rngs::StdRng, SeedableRng};
#[test]
fn standard_normal_is_finite_and_centered() {
let mut rng = StdRng::seed_from_u64(42);
let n = 10_000;
let samples: Vec<f64> = (0..n).map(|_| standard_normal(&mut rng)).collect();
assert!(samples.iter().all(|sample| sample.is_finite()));
let mean = samples.iter().sum::<f64>() / n as f64;
assert!(mean.abs() < 0.05, "mean too far from zero: {mean}");
let variance = samples
.iter()
.map(|sample| {
let delta = sample - mean;
delta * delta
})
.sum::<f64>()
/ n as f64;
assert!(
(0.90..=1.10).contains(&variance),
"variance should be near one, got {variance}"
);
}
#[test]
fn cv_undefined_for_degenerate_samples() {
assert_eq!(coefficient_of_variation(&[]), None, "empty has no CV");
assert_eq!(coefficient_of_variation(&[5.0]), None, "single point has no CV");
assert_eq!(
coefficient_of_variation(&[0.0, 0.0]),
None,
"zero mean makes CV undefined"
);
}
#[test]
fn cv_zero_for_constant_stream() {
let cv = coefficient_of_variation(&[100.0, 100.0, 100.0, 100.0]).unwrap();
assert!(cv.abs() < 1e-9, "constant stream CV {cv} should be 0");
assert!(cv < HUMAN_TIMING_CV_FLOOR);
}
#[test]
fn cv_matches_hand_computed_value() {
let cv = coefficient_of_variation(&[2.0, 3.0, 4.0]).unwrap();
assert!((cv - 0.272_166).abs() < 1e-4, "CV {cv} != hand value");
assert!(cv >= HUMAN_TIMING_CV_FLOOR, "spread-out stream clears floor");
}
#[test]
fn cv_drift_floor_below_human_floor() {
assert!(CV_DRIFT_FLOOR < HUMAN_TIMING_CV_FLOOR);
}
}