rand_distr/
unit_disc.rs

1// Copyright 2019 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 unit disc in two dimensions.
14///
15/// Implemented via rejection sampling.
16///
17/// For a distribution that samples only from the circumference of the unit disc,
18/// see [`UnitCircle`](crate::UnitCircle).
19///
20/// For a similar distribution in three dimensions, see [`UnitBall`](crate::UnitBall).
21///
22/// # Plot
23///
24/// The following plot shows the unit disc.
25/// This distribution samples individual points from the entire area of the disc.
26///
27/// ![Unit disc](https://raw.githubusercontent.com/rust-random/charts/main/charts/unit_disc.svg)
28///
29/// # Example
30///
31/// ```
32/// use rand_distr::{UnitDisc, Distribution};
33///
34/// let v: [f64; 2] = UnitDisc.sample(&mut rand::rng());
35/// println!("{:?} is from the unit Disc.", v)
36/// ```
37#[derive(Clone, Copy, Debug)]
38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
39pub struct UnitDisc;
40
41impl<F: Float + SampleUniform> Distribution<[F; 2]> for UnitDisc {
42    #[inline]
43    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> [F; 2] {
44        let uniform = Uniform::new(F::from(-1.).unwrap(), F::from(1.).unwrap()).unwrap();
45        let mut x1;
46        let mut x2;
47        loop {
48            x1 = uniform.sample(rng);
49            x2 = uniform.sample(rng);
50            if x1 * x1 + x2 * x2 <= F::from(1.).unwrap() {
51                break;
52            }
53        }
54        [x1, x2]
55    }
56}