rust-average/tests/mean.rs

61 lines
1.8 KiB
Rust
Raw Normal View History

2017-05-30 10:54:14 +02:00
#![cfg_attr(feature = "cargo-clippy", allow(float_cmp, map_clone))]
2017-05-05 16:40:23 +02:00
#[macro_use] extern crate average;
2017-05-19 15:54:13 +02:00
extern crate core;
use core::iter::Iterator;
2017-05-28 21:13:47 +02:00
use average::MeanWithError;
2017-05-19 15:54:13 +02:00
#[test]
fn trivial() {
2017-05-28 21:13:47 +02:00
let mut a = MeanWithError::new();
2017-05-19 15:54:13 +02:00
assert_eq!(a.len(), 0);
a.add(1.0);
assert_eq!(a.mean(), 1.0);
assert_eq!(a.len(), 1);
assert_eq!(a.sample_variance(), 0.0);
assert_eq!(a.population_variance(), 0.0);
assert_eq!(a.error(), 0.0);
a.add(1.0);
assert_eq!(a.mean(), 1.0);
assert_eq!(a.len(), 2);
assert_eq!(a.sample_variance(), 0.0);
assert_eq!(a.population_variance(), 0.0);
assert_eq!(a.error(), 0.0);
2017-05-05 16:40:23 +02:00
}
#[test]
2017-05-19 15:54:13 +02:00
fn simple() {
2017-05-28 21:13:47 +02:00
let a: MeanWithError = (1..6).map(f64::from).collect();
2017-05-19 15:54:13 +02:00
assert_eq!(a.mean(), 3.0);
assert_eq!(a.len(), 5);
assert_eq!(a.sample_variance(), 2.5);
assert_almost_eq!(a.error(), f64::sqrt(0.5), 1e-16);
2017-05-05 16:40:23 +02:00
}
#[test]
2017-05-19 15:54:13 +02:00
fn numerically_unstable() {
// The naive algorithm fails for this example due to cancelation.
let big = 1e9;
let sample = &[big + 4., big + 7., big + 13., big + 16.];
2017-05-28 21:13:47 +02:00
let a: MeanWithError = sample.iter().map(|x| *x).collect();
2017-05-19 15:54:13 +02:00
assert_eq!(a.sample_variance(), 30.);
}
#[test]
fn merge() {
let sequence: &[f64] = &[1., 2., 3., 4., 5., 6., 7., 8., 9.];
for mid in 0..sequence.len() {
let (left, right) = sequence.split_at(mid);
2017-05-28 21:13:47 +02:00
let avg_total: MeanWithError = sequence.iter().map(|x| *x).collect();
let mut avg_left: MeanWithError = left.iter().map(|x| *x).collect();
let avg_right: MeanWithError = right.iter().map(|x| *x).collect();
avg_left.merge(&avg_right);
assert_eq!(avg_total.len(), avg_left.len());
assert_eq!(avg_total.mean(), avg_left.mean());
assert_eq!(avg_total.sample_variance(), avg_left.sample_variance());
}
}