Skip to content

Commit 41aaa3c

Browse files
committed
Add uniformity test for unit sphere and circle
1 parent 5e9c2e1 commit 41aaa3c

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

Cargo.toml

+2
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ wasm-bindgen = { version = "0.2.12", optional = true }
5858
# This is for testing serde, unfortunately we can't specify feature-gated dev
5959
# deps yet, see: https://github.com/rust-lang/cargo/issues/1596
6060
bincode = "1.0"
61+
# This has a histogram implementation used for testing uniformity.
62+
average = "0.9.1"
6163

6264
[package.metadata.docs.rs]
6365
all-features = true

tests/uniformity.rs

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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

Comments
 (0)