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 num_traits::Float;
10use crate::{uniform::SampleUniform, Distribution, Uniform};
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///
18/// # Example
19///
20/// ```
21/// use rand_distr::{UnitSphere, Distribution};
22///
23/// let v: [f64; 3] = UnitSphere.sample(&mut rand::thread_rng());
24/// println!("{:?} is from the unit sphere surface.", v)
25/// ```
26///
27/// [^1]: Marsaglia, George (1972). [*Choosing a Point from the Surface of a
28///       Sphere.*](https://doi.org/10.1214/aoms/1177692644)
29///       Ann. Math. Statist. 43, no. 2, 645--646.
30#[derive(Clone, Copy, Debug)]
31#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
32pub struct UnitSphere;
33
34impl<F: Float + SampleUniform> Distribution<[F; 3]> for UnitSphere {
35    #[inline]
36    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> [F; 3] {
37        let uniform = Uniform::new(F::from(-1.).unwrap(), F::from(1.).unwrap());
38        loop {
39            let (x1, x2) = (uniform.sample(rng), uniform.sample(rng));
40            let sum = x1 * x1 + x2 * x2;
41            if sum >= F::from(1.).unwrap() {
42                continue;
43            }
44            let factor = F::from(2.).unwrap() * (F::one() - sum).sqrt();
45            return [x1 * factor, x2 * factor, F::from(1.).unwrap() - F::from(2.).unwrap() * sum];
46        }
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::UnitSphere;
53    use crate::Distribution;
54
55    #[test]
56    fn norm() {
57        let mut rng = crate::test::rng(1);
58        for _ in 0..1000 {
59            let x: [f64; 3] = UnitSphere.sample(&mut rng);
60            assert_almost_eq!(x[0] * x[0] + x[1] * x[1] + x[2] * x[2], 1., 1e-15);
61        }
62    }
63}