1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 /*
19 * This is not the original file distributed by the Apache Software Foundation
20 * It has been modified by the Hipparchus project
21 */
22
23 package org.hipparchus.random;
24
25 import org.hipparchus.util.FastMath;
26
27
28 /**
29 * Generate random vectors isotropically located on the surface of a sphere.
30 */
31 public class UnitSphereRandomVectorGenerator
32 implements RandomVectorGenerator {
33
34 /** RNG used for generating the individual components of the vectors. */
35 private final RandomGenerator rand;
36 /** Space dimension. */
37 private final int dimension;
38
39 /** Simple constructor.
40 * @param dimension Space dimension.
41 * @param rand RNG for the individual components of the vectors.
42 */
43 public UnitSphereRandomVectorGenerator(final int dimension,
44 final RandomGenerator rand) {
45 this.dimension = dimension;
46 this.rand = rand;
47 }
48
49 /**
50 * Create an object that will use a default RNG ({@link MersenneTwister}),
51 * in order to generate the individual components.
52 *
53 * @param dimension Space dimension.
54 */
55 public UnitSphereRandomVectorGenerator(final int dimension) {
56 this(dimension, new MersenneTwister());
57 }
58
59 /** {@inheritDoc} */
60 @Override
61 public double[] nextVector() {
62 final double[] v = new double[dimension];
63
64 // See http://mathworld.wolfram.com/SpherePointPicking.html for example.
65 // Pick a point by choosing a standard Gaussian for each element, and then
66 // normalizing to unit length.
67 double normSq = 0;
68 for (int i = 0; i < dimension; i++) {
69 final double comp = rand.nextGaussian();
70 v[i] = comp;
71 normSq += comp * comp;
72 }
73
74 final double f = 1 / FastMath.sqrt(normSq);
75 for (int i = 0; i < dimension; i++) {
76 v[i] *= f;
77 }
78
79 return v;
80 }
81 }