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