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