Skip to content

Commit f8767d0

Browse files
committed
Add uniformity test for unit sphere and circle
This introduces an external dev-dependency on the `average` crate.
1 parent 4dfec8a commit f8767d0

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

Cargo.toml

+4
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@ fuchsia-zircon = { version = "0.3.2", optional = true }
5555
stdweb = { version = "0.4", optional = true }
5656
wasm-bindgen = { version = "0.2.12", optional = true }
5757

58+
[dev-dependencies]
59+
# This has a histogram implementation used for testing uniformity.
60+
average = "0.9.2"
61+
5862
[build-dependencies]
5963
rustc_version = "0.2"
6064

tests/uniformity.rs

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

Comments
 (0)