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
Provenance
- Commit
f48f44b- Tree
beb7c86- Author
David Peter <sharkdp@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent 1
efd57b3- Parent 2
0fe93f9
2 files changed+35 added−29 removed
modified:src/benchmark/measurement.rs+5 added-4 removed
52 unmodified lines53 pub fn time_wall_clock_mean(&self) -> Time {54 mean(self.wall_clock_times())55 }56 57- /// 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 collecting60+59- 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(×, self.time_wall_clock_mean()))64+ Some(standard_deviation(times))65 }66 }67 68 /// The median wall clock time.33 unmodified linesmodified:src/quantity/statistics.rs+30 added-25 removed
1-//! Statistics for non-empty samples of finite measurements.1+use std::ops::Add;2+use std::ops::AddAssign;3+use std::ops::Div;4 3-use std::ops::{Add, AddAssign, Div};5+use uom::num_traits;6+use uom::si::f64::Ratio;7+use uom::si::ratio::ratio;8 5-use crate::quantity::{byte, ratio, second, Information, Ratio, Time, Zero};9+use super::{byte, second, Information, Time};10 11 /// A min function that assumes no NaNs and at least one element12 pub fn min<Q: PartialOrd>(values: impl IntoIterator<Item = Q>) -> Q {13 values9 unmodified lines23 .max_by(|a, b| a.partial_cmp(b).expect("No NaN values"))24 .expect("'max' requires at least one element")25 }26 23-/// Arithmetic mean, summing measurements in their original order.27+/// A mean function that assumes at least one element28 pub fn mean<Q, P>(values: impl IntoIterator<Item = Q>) -> Q29 where26- 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 line40 let count = Ratio::new::<ratio>(count as f64);41 (sum / count).into()42 }43 40-/// Median without modifying the input sample.44 pub fn median<Q, P>(values: impl IntoIterator<Item = Q>) -> Q45 where46 Q: Copy + PartialOrd + Add<Output = Q> + Div<Ratio, Output = P>,47 P: Into<Q>,2 unmodified lines50 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"));55 56 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 lines90 Information::new::<byte>(value)91 }92 }93 91-/// Sample standard deviation, using an already computed mean.92-pub 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");94+fn standard_deviation_f64(values: &[f64]) -> f64 {95+ let mean_value = mean(values.iter().copied());96 104- // 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+ }104+105+ (1. / ((n - 1) as f64) * squared_deviations).sqrt()106 }107 108+pub 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+}113+114 /// 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 lines223 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 }