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