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 */
017package org.apache.commons.rng.sampling.distribution;
018
019import org.apache.commons.rng.UniformRandomProvider;
020
021/**
022 * <a href="https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform">
023 * Box-Muller algorithm</a> for sampling from Gaussian distribution with
024 * mean 0 and standard deviation 1.
025 *
026 * <p>Sampling uses:</p>
027 *
028 * <ul>
029 *   <li>{@link UniformRandomProvider#nextDouble()}
030 *   <li>{@link UniformRandomProvider#nextLong()}
031 * </ul>
032 *
033 * @since 1.1
034 */
035public class BoxMullerNormalizedGaussianSampler
036    implements NormalizedGaussianSampler, SharedStateContinuousSampler {
037    /** Next gaussian. */
038    private double nextGaussian = Double.NaN;
039    /** Underlying source of randomness. */
040    private final UniformRandomProvider rng;
041
042    /**
043     * Create an instance.
044     *
045     * @param rng Generator of uniformly distributed random numbers.
046     */
047    public BoxMullerNormalizedGaussianSampler(UniformRandomProvider rng) {
048        this.rng = rng;
049    }
050
051    /** {@inheritDoc} */
052    @Override
053    public double sample() {
054        final double random;
055        if (Double.isNaN(nextGaussian)) {
056            // Generate a pair of Gaussian numbers.
057
058            // Avoid zero for the uniform deviate y.
059            // The extreme tail of the sample is:
060            // y = 2^-53
061            // r = 8.57167
062            final double x = rng.nextDouble();
063            final double y = InternalUtils.makeNonZeroDouble(rng.nextLong());
064            final double alpha = 2 * Math.PI * x;
065            final double r = Math.sqrt(-2 * Math.log(y));
066
067            // Return the first element of the generated pair.
068            random = r * Math.cos(alpha);
069
070            // Keep second element of the pair for next invocation.
071            nextGaussian = r * Math.sin(alpha);
072        } else {
073            // Use the second element of the pair (generated at the
074            // previous invocation).
075            random = nextGaussian;
076
077            // Both elements of the pair have been used.
078            nextGaussian = Double.NaN;
079        }
080
081        return random;
082    }
083
084    /** {@inheritDoc} */
085    @Override
086    public String toString() {
087        return "Box-Muller normalized Gaussian deviate [" + rng.toString() + "]";
088    }
089
090    /**
091     * {@inheritDoc}
092     *
093     * @since 1.3
094     */
095    @Override
096    public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) {
097        return new BoxMullerNormalizedGaussianSampler(rng);
098    }
099
100    /**
101     * Create a new normalised Gaussian sampler.
102     *
103     * @param <S> Sampler type.
104     * @param rng Generator of uniformly distributed random numbers.
105     * @return the sampler
106     * @since 1.3
107     */
108    @SuppressWarnings("unchecked")
109    public static <S extends NormalizedGaussianSampler & SharedStateContinuousSampler> S
110            of(UniformRandomProvider rng) {
111        return (S) new BoxMullerNormalizedGaussianSampler(rng);
112    }
113}