rand_distr/
unit_sphere.rs

1// Copyright 2018-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 surface of the unit sphere in three dimensions.
14///
15/// Implemented via a method by Marsaglia[^1].
16///
17/// For a distribution that also samples from the interior of the sphere,
18/// see [`UnitBall`](crate::UnitBall).
19///
20/// For a similar distribution in two dimensions, see [`UnitCircle`](crate::UnitCircle).
21///
22/// # Plot
23///
24/// The following plot shows the unit sphere as a wireframe.
25/// The wireframe is meant to illustrate that this distribution samples
26/// from the surface of the sphere only, not from the interior.
27///
28/// ![Unit sphere](https://raw.githubusercontent.com/rust-random/charts/main/charts/unit_sphere.svg)
29///
30/// # Example
31///
32/// ```
33/// use rand_distr::{UnitSphere, Distribution};
34///
35/// let v: [f64; 3] = UnitSphere.sample(&mut rand::rng());
36/// println!("{:?} is from the unit sphere surface.", v)
37/// ```
38///
39/// [^1]: Marsaglia, George (1972). [*Choosing a Point from the Surface of a
40///       Sphere.*](https://doi.org/10.1214/aoms/1177692644)
41///       Ann. Math. Statist. 43, no. 2, 645--646.
42#[derive(Clone, Copy, Debug)]
43#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
44pub struct UnitSphere;
45
46impl<F: Float + SampleUniform> Distribution<[F; 3]> for UnitSphere {
47    #[inline]
48    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> [F; 3] {
49        let uniform = Uniform::new(F::from(-1.).unwrap(), F::from(1.).unwrap()).unwrap();
50        loop {
51            let (x1, x2) = (uniform.sample(rng), uniform.sample(rng));
52            let sum = x1 * x1 + x2 * x2;
53            if sum >= F::from(1.).unwrap() {
54                continue;
55            }
56            let factor = F::from(2.).unwrap() * (F::one() - sum).sqrt();
57            return [
58                x1 * factor,
59                x2 * factor,
60                F::from(1.).unwrap() - F::from(2.).unwrap() * sum,
61            ];
62        }
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::UnitSphere;
69    use crate::Distribution;
70
71    #[test]
72    fn norm() {
73        let mut rng = crate::test::rng(1);
74        for _ in 0..1000 {
75            let x: [f64; 3] = UnitSphere.sample(&mut rng);
76            assert_almost_eq!(x[0] * x[0] + x[1] * x[1] + x[2] * x[2], 1., 1e-15);
77        }
78    }
79}