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