| 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 |
use num_traits::Float; |
| 10 |
use crate::{uniform::SampleUniform, Distribution, Uniform}; |
| 11 |
use rand::Rng; |
| 12 |
|
| 13 |
/// Samples uniformly from the edge of the unit circle in two dimensions. |
| 14 |
/// |
| 15 |
/// Implemented via a method by von Neumann[^1]. |
| 16 |
/// |
| 17 |
/// |
| 18 |
/// # Example |
| 19 |
/// |
| 20 |
/// ``` |
| 21 |
/// use rand_distr::{UnitCircle, Distribution}; |
| 22 |
/// |
| 23 |
/// let v: [f64; 2] = UnitCircle.sample(&mut rand::thread_rng()); |
| 24 |
/// println!("{:?} is from the unit circle.", v) |
| 25 |
/// ``` |
| 26 |
/// |
| 27 |
/// [^1]: von Neumann, J. (1951) [*Various Techniques Used in Connection with |
| 28 |
/// Random Digits.*](https://mcnp.lanl.gov/pdf_files/nbs_vonneumann.pdf) |
| 29 |
/// NBS Appl. Math. Ser., No. 12. Washington, DC: U.S. Government Printing |
| 30 |
/// Office, pp. 36-38. |
| 31 |
#[derive(Clone, Copy, Debug)] |
| 32 |
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))] |
| 33 |
pub struct UnitCircle; |
| 34 |
|
| 35 |
impl<F: Float + SampleUniform> Distribution<[F; 2]> for UnitCircle { |
| 36 |
#[inline] |
| 37 |
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> [F; 2] { |
| 38 |
let uniform = Uniform::new(F::from(-1.).unwrap(), F::from(1.).unwrap()); |
| 39 |
let mut x1; |
| 40 |
let mut x2; |
| 41 |
let mut sum; |
| 42 |
loop { |
| 43 |
x1 = uniform.sample(rng); |
| 44 |
x2 = uniform.sample(rng); |
| 45 |
sum = x1 * x1 + x2 * x2; |
| 46 |
if sum < F::from(1.).unwrap() { |
| 47 |
break; |
| 48 |
} |
| 49 |
} |
| 50 |
let diff = x1 * x1 - x2 * x2; |
| 51 |
[diff / sum, F::from(2.).unwrap() * x1 * x2 / sum] |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
#[cfg(test)] |
| 56 |
mod tests { |
| 57 |
use super::UnitCircle; |
| 58 |
use crate::Distribution; |
| 59 |
|
| 60 |
#[test] |
| 61 |
fn norm() { |
| 62 |
let mut rng = crate::test::rng(1); |
| 63 |
for _ in 0..1000 { |
| 64 |
let x: [f64; 2] = UnitCircle.sample(&mut rng); |
| 65 |
assert_almost_eq!(x[0] * x[0] + x[1] * x[1], 1., 1e-15); |
| 66 |
} |
| 67 |
} |
| 68 |
} |