]> git.proxmox.com Git - rustc.git/blob - vendor/rand-0.6.1/tests/uniformity.rs
New upstream version 1.46.0+dfsg1
[rustc.git] / vendor / rand-0.6.1 / tests / uniformity.rs
1 // Copyright 2018 Developers of the Rand project.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8
9 #![cfg(feature = "std")]
10
11 #[macro_use]
12 extern crate average;
13 extern crate rand;
14
15 use std as core;
16 use rand::FromEntropy;
17 use rand::distributions::Distribution;
18 use average::Histogram;
19
20 const N_BINS: usize = 100;
21 const N_SAMPLES: u32 = 1_000_000;
22 const TOL: f64 = 1e-3;
23 define_histogram!(hist, 100);
24 use hist::Histogram as Histogram100;
25
26 #[test]
27 fn unit_sphere() {
28 const N_DIM: usize = 3;
29 let h = Histogram100::with_const_width(-1., 1.);
30 let mut histograms = [h.clone(), h.clone(), h];
31 let dist = rand::distributions::UnitSphereSurface::new();
32 let mut rng = rand::rngs::SmallRng::from_entropy();
33 for _ in 0..N_SAMPLES {
34 let v = dist.sample(&mut rng);
35 for i in 0..N_DIM {
36 histograms[i].add(v[i]).map_err(
37 |e| { println!("v: {}", v[i]); e }
38 ).unwrap();
39 }
40 }
41 for h in &histograms {
42 let sum: u64 = h.bins().iter().sum();
43 println!("{:?}", h);
44 for &b in h.bins() {
45 let p = (b as f64) / (sum as f64);
46 assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, "{}", p);
47 }
48 }
49 }
50
51 #[test]
52 fn unit_circle() {
53 use ::std::f64::consts::PI;
54 let mut h = Histogram100::with_const_width(-PI, PI);
55 let dist = rand::distributions::UnitCircle::new();
56 let mut rng = rand::rngs::SmallRng::from_entropy();
57 for _ in 0..N_SAMPLES {
58 let v = dist.sample(&mut rng);
59 h.add(v[0].atan2(v[1])).unwrap();
60 }
61 let sum: u64 = h.bins().iter().sum();
62 println!("{:?}", h);
63 for &b in h.bins() {
64 let p = (b as f64) / (sum as f64);
65 assert!((p - 1.0 / (N_BINS as f64)).abs() < TOL, "{}", p);
66 }
67 }