|
| 1 | +#![cfg(feature = "std")] |
| 2 | + |
| 3 | +#[macro_use] |
| 4 | +extern crate average; |
| 5 | +extern crate rand; |
| 6 | + |
| 7 | +use std as core; |
| 8 | +use rand::FromEntropy; |
| 9 | +use rand::distributions::Distribution; |
| 10 | +use average::Histogram; |
| 11 | + |
| 12 | +const N_BINS: usize = 100; |
| 13 | +const N_SAMPLES: u32 = 1_000_000; |
| 14 | +const TOL: f64 = 1e-3; |
| 15 | +define_histogram!(hist, 100); |
| 16 | +use hist::Histogram as Histogram100; |
| 17 | + |
| 18 | +#[test] |
| 19 | +fn unit_sphere() { |
| 20 | + const N_DIM: usize = 3; |
| 21 | + let h = Histogram100::with_const_width(-1., 1.); |
| 22 | + let mut histograms = [h.clone(), h.clone(), h]; |
| 23 | + let dist = rand::distributions::UnitSphereSurface::new(); |
| 24 | + let mut rng = rand::rngs::SmallRng::from_entropy(); |
| 25 | + for _ in 0..N_SAMPLES { |
| 26 | + let v = dist.sample(&mut rng); |
| 27 | + for i in 0..N_DIM { |
| 28 | + histograms[i].add(v[i]).map_err( |
| 29 | + |e| { println!("v: {}", v[i]); e } |
| 30 | + ).unwrap(); |
| 31 | + } |
| 32 | + } |
| 33 | + for h in &histograms { |
| 34 | + let sum: u64 = h.bins().iter().sum(); |
| 35 | + println!("{:?}", h); |
| 36 | + for &b in h.bins() { |
| 37 | + let p = (b as f64) / (sum as f64); |
| 38 | + assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, "{}", p); |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +#[test] |
| 44 | +fn unit_circle() { |
| 45 | + use ::std::f64::consts::PI; |
| 46 | + let mut h = Histogram100::with_const_width(-PI, PI); |
| 47 | + let dist = rand::distributions::UnitCircle::new(); |
| 48 | + let mut rng = rand::rngs::SmallRng::from_entropy(); |
| 49 | + for _ in 0..N_SAMPLES { |
| 50 | + let v = dist.sample(&mut rng); |
| 51 | + h.add(v[0].atan2(v[1])).unwrap(); |
| 52 | + } |
| 53 | + let sum: u64 = h.bins().iter().sum(); |
| 54 | + println!("{:?}", h); |
| 55 | + for &b in h.bins() { |
| 56 | + let p = (b as f64) / (sum as f64); |
| 57 | + assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, "{}", p); |
| 58 | + } |
| 59 | +} |
0 commit comments