rust-average/tests/random.rs

37 lines
1.2 KiB
Rust
Raw Normal View History

2017-05-30 10:54:14 +02:00
#![cfg_attr(feature = "cargo-clippy", allow(float_cmp, map_clone))]
2019-07-08 16:01:13 +02:00
use rand_distr::Distribution;
2018-07-06 10:31:26 +02:00
2019-07-08 16:17:04 +02:00
use average::{Kurtosis, Estimate, assert_almost_eq};
2017-05-28 23:46:15 +02:00
#[test]
fn normal_distribution() {
2019-07-08 16:01:13 +02:00
let normal = rand_distr::Normal::new(2.0, 3.0).unwrap();
2017-05-28 23:46:15 +02:00
let mut a = Kurtosis::new();
for _ in 0..1_000_000 {
2018-07-06 10:31:26 +02:00
a.add(normal.sample(&mut ::rand::thread_rng()));
2017-05-28 23:46:15 +02:00
}
assert_almost_eq!(a.mean(), 2.0, 1e-2);
assert_almost_eq!(a.sample_variance().sqrt(), 3.0, 1e-2);
assert_almost_eq!(a.population_variance().sqrt(), 3.0, 1e-2);
assert_almost_eq!(a.error_mean(), 0.0, 1e-2);
assert_almost_eq!(a.skewness(), 0.0, 1e-2);
assert_almost_eq!(a.kurtosis(), 0.0, 4e-2);
}
#[test]
fn exponential_distribution() {
let lambda = 2.0;
2019-07-08 16:01:13 +02:00
let normal = rand_distr::Exp::new(lambda).unwrap();
2017-05-28 23:46:15 +02:00
let mut a = Kurtosis::new();
for _ in 0..6_000_000 {
2018-07-06 10:31:26 +02:00
a.add(normal.sample(&mut ::rand::thread_rng()));
2017-05-28 23:46:15 +02:00
}
assert_almost_eq!(a.mean(), 1./lambda, 1e-2);
assert_almost_eq!(a.sample_variance().sqrt(), 1./lambda, 1e-2);
assert_almost_eq!(a.population_variance().sqrt(), 1./lambda, 1e-2);
assert_almost_eq!(a.error_mean(), 0.0, 1e-2);
assert_almost_eq!(a.skewness(), 2.0, 1e-1);
2017-05-28 23:46:15 +02:00
assert_almost_eq!(a.kurtosis(), 6.0, 1e-1);
}