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 a Gaussian distribution. 024 */ 025public class BoxMullerGaussianSampler 026 extends SamplerBase 027 implements ContinuousSampler { 028 /** Next gaussian. */ 029 private double nextGaussian = Double.NaN; 030 /** Mean. */ 031 private final double mean; 032 /** standardDeviation. */ 033 private final double standardDeviation; 034 035 /** 036 * @param rng Generator of uniformly distributed random numbers. 037 * @param mean Mean of the Gaussian distribution. 038 * @param standardDeviation Standard deviation of the Gaussian distribution. 039 */ 040 public BoxMullerGaussianSampler(UniformRandomProvider rng, 041 double mean, 042 double standardDeviation) { 043 super(rng); 044 this.mean = mean; 045 this.standardDeviation = standardDeviation; 046 } 047 048 /** {@inheritDoc} */ 049 @Override 050 public double sample() { 051 final double random; 052 if (Double.isNaN(nextGaussian)) { 053 // Generate a pair of Gaussian numbers. 054 055 final double x = nextDouble(); 056 final double y = nextDouble(); 057 final double alpha = 2 * Math.PI * x; 058 final double r = Math.sqrt(-2 * Math.log(y)); 059 060 // Return the first element of the generated pair. 061 random = r * Math.cos(alpha); 062 063 // Keep second element of the pair for next invocation. 064 nextGaussian = r * Math.sin(alpha); 065 } else { 066 // Use the second element of the pair (generated at the 067 // previous invocation). 068 random = nextGaussian; 069 070 // Both elements of the pair have been used. 071 nextGaussian = Double.NaN; 072 } 073 074 return standardDeviation * random + mean; 075 } 076 077 /** {@inheritDoc} */ 078 @Override 079 public String toString() { 080 return "Box-Muller Gaussian deviate [" + super.toString() + "]"; 081 } 082}