001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.math3.random;
019
020import org.apache.commons.math3.util.FastMath;
021
022
023/**
024 * Generate random vectors isotropically located on the surface of a sphere.
025 *
026 * @since 2.1
027 */
028
029public class UnitSphereRandomVectorGenerator
030    implements RandomVectorGenerator {
031    /**
032     * RNG used for generating the individual components of the vectors.
033     */
034    private final RandomGenerator rand;
035    /**
036     * Space dimension.
037     */
038    private final int dimension;
039
040    /**
041     * @param dimension Space dimension.
042     * @param rand RNG for the individual components of the vectors.
043     */
044    public UnitSphereRandomVectorGenerator(final int dimension,
045                                           final RandomGenerator rand) {
046        this.dimension = dimension;
047        this.rand = rand;
048    }
049    /**
050     * Create an object that will use a default RNG ({@link MersenneTwister}),
051     * in order to generate the individual components.
052     *
053     * @param dimension Space dimension.
054     */
055    public UnitSphereRandomVectorGenerator(final int dimension) {
056        this(dimension, new MersenneTwister());
057    }
058
059    /** {@inheritDoc} */
060    public double[] nextVector() {
061        final double[] v = new double[dimension];
062
063        // See http://mathworld.wolfram.com/SpherePointPicking.html for example.
064        // Pick a point by choosing a standard Gaussian for each element, and then
065        // normalizing to unit length.
066        double normSq = 0;
067        for (int i = 0; i < dimension; i++) {
068            final double comp = rand.nextGaussian();
069            v[i] = comp;
070            normSq += comp * comp;
071        }
072
073        final double f = 1 / FastMath.sqrt(normSq);
074        for (int i = 0; i < dimension; i++) {
075            v[i] *= f;
076        }
077
078        return v;
079    }
080}