Skip to content

Commit f553739

Browse files
committed
Add uniformity test for unit sphere and circle
1 parent d287e4d commit f553739

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,5 +53,9 @@ fuchsia-zircon = { version = "0.3.2", optional = true }
5353
stdweb = { version = "0.4", optional = true }
5454
wasm-bindgen = { version = "0.2.12", optional = true }
5555

56+
[dev-dependencies]
57+
# This has a histogram implementation used for testing uniformity.
58+
average = "0.9.1"
59+
5660
[package.metadata.docs.rs]
5761
all-features = true

tests/uniformity.rs

Lines changed: 57 additions & 0 deletions
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)