Skip to content
Myr

Merge pull request #976 from sharkdp/codex/remaining-statistics

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Compute standard deviation directly from samples

authored by David Peter · committed by GitHub · parents efd57b3, 0fe93f9 · Browse files · 2 files+35 added−29 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+35 added−29 removed

  • other:+35 added−29 removed

2 files+35 added−29 removed

modified:src/benchmark/measurement.rs+5 added-4 removed
52 unmodified lines
53 pub fn time_wall_clock_mean(&self) -> Time {54 mean(self.wall_clock_times())55 }5657 /// The standard deviation of wall clock times, if at least two runs were measured.57 /// The standard deviation of all wall clock times. Not available if only one run has been performed58 pub fn stddev(&self) -> Option<Time> {59 let times: Vec<_> = self.wall_clock_times().collect(); // TODO: Avoid collecting6059 if self.len() < 2 {61 if times.len() < 2 {62 None63 } else {62 let times: Vec<_> = self.wall_clock_times().collect();63 Some(standard_deviation(&times, self.time_wall_clock_mean()))64 Some(standard_deviation(times))65 }66 }6768 /// The median wall clock time.
33 unmodified lines
modified:src/quantity/statistics.rs+30 added-25 removed
1//! Statistics for non-empty samples of finite measurements.1use std::ops::Add;2use std::ops::AddAssign;3use std::ops::Div;43use std::ops::{Add, AddAssign, Div};5use uom::num_traits;6use uom::si::f64::Ratio;7use uom::si::ratio::ratio;85use crate::quantity::{byte, ratio, second, Information, Ratio, Time, Zero};9use super::{byte, second, Information, Time};1011/// A min function that assumes no NaNs and at least one element12pub fn min<Q: PartialOrd>(values: impl IntoIterator<Item = Q>) -> Q {13 values
9 unmodified lines
23 .max_by(|a, b| a.partial_cmp(b).expect("No NaN values"))24 .expect("'max' requires at least one element")25}2623/// Arithmetic mean, summing measurements in their original order.27/// A mean function that assumes at least one element28pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q29where26 Q: AddAssign + Zero + Div<Ratio, Output = P>,30 Q: AddAssign + num_traits::Zero + Div<Ratio, Output = P>,31 P: Into<Q>,32{33 let mut sum = Q::zero();30 let mut count = 0usize;34 let mut count = 0;35 for value in values {36 sum += value;37 count += 1;38 }
1 unmodified line
40 let count = Ratio::new::<ratio>(count as f64);41 (sum / count).into()42}4340/// Median without modifying the input sample.44pub fn median<Q, P>(values: impl IntoIterator<Item = Q>) -> Q45where46 Q: Copy + PartialOrd + Add<Output = Q> + Div<Ratio, Output = P>,47 P: Into<Q>,
2 unmodified lines
50 assert!(51 !values.is_empty(),52 "median requires at least one measurement"53 );51 values.sort_unstable_by(|a, b| a.partial_cmp(b).expect("No NaN measurements"));54 values.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values"));5556 let len = values.len();57 if len % 2 == 0 {58 let mid = len / 2;59 let a = &values[mid - 1];60 let b = &values[mid];58 ((*b + *a) / Ratio::new::<ratio>(2.)).into()61 ((*a + *b) / Ratio::new::<ratio>(2.)).into()62 } else {63 values[len / 2]64 }65}
24 unmodified lines
90 Information::new::<byte>(value)91 }92}9391/// Sample standard deviation, using an already computed mean.92pub fn standard_deviation<Q: UnsafeRawValue>(values: &[Q], mean: Q) -> Q {93 let mean = mean.unsafe_raw_value();94 assert!(95 values.len() > 1,96 "standard deviation requires at least two measurements"97 );98 let sum = values99 .iter()100 .map(|value| (value.unsafe_raw_value() - mean) * (value.unsafe_raw_value() - mean))101 .fold(0.0, |sum, deviation| sum + deviation);102 assert!(sum >= 0.0, "invalid sum of squared deviations");94fn standard_deviation_f64(values: &[f64]) -> f64 {95 let mean_value = mean(values.iter().copied());96104 // Preserve the operation order of statistical 1.0: dividing by n - 1105 // before taking the square root also preserves exported floating-point values.106 Q::unsafe_from_raw_value((sum / (values.len() as f64 - 1.0)).sqrt())97 let mut squared_deviations = 0.;98 let mut n = 0;99 for value in values {100 let deviation = value - mean_value;101 squared_deviations += deviation * deviation;102 n += 1;103 }104105 (1. / ((n - 1) as f64) * squared_deviations).sqrt()106}107108pub fn standard_deviation<Q: UnsafeRawValue>(values: impl IntoIterator<Item = Q> + Clone) -> Q {109 let values: Vec<_> = values.into_iter().map(|q| q.unsafe_raw_value()).collect();110 let result = standard_deviation_f64(&values);111 Q::unsafe_from_raw_value(result)112}113114/// Compute modified Z-scores for a given sample. A (unmodified) Z-score is defined by115/// `(x_i - x_mean)/x_stddev` whereas the modified Z-score is defined by `(x_i - x_median)/MAD`116/// where MAD is the median absolute deviation.117///
105 unmodified lines
223 Time::new::<millisecond>(100.0),224 Time::new::<millisecond>(200.0),225 Time::new::<microsecond>(300_000.0),226 ];222 let result = standard_deviation(&values, mean(values));227 let result = standard_deviation(values);228 assert_relative_eq!(result.get::<millisecond>(), 100.0);229 }230}