# Box–Muller transform

The **Box–Muller transform**, by George Edward Pelham Box and Mervin Edgar Muller,^{[1]} is a pseudo-random number sampling method for generating pairs of independent, standard, normally distributed (zero expectation, unit variance) random numbers, given a source of uniformly distributed random numbers. The method was in fact first mentioned explicitly by Raymond E. A. C. Paley and Norbert Wiener in 1934.^{[2]}

The Box–Muller transform is commonly expressed in two forms; the basic form as given by Box and Muller takes two samples from the uniform distribution on the interval [0, 1] and maps them to two standard, normally distributed samples. The polar form takes two samples from a different interval, [−1, +1], and maps them to two normally distributed samples without the use of sine or cosine functions.

The Box–Muller transform was developed as a more computationally efficient alternative to the inverse transform sampling method;^{[3]} the ziggurat algorithm gives a more efficient method for CPU, while the Box-Muller transform is superior for GPU^{[4]}. Furthermore, the Box–Muller transform can be employed for drawing from truncated bivariate Gaussian densities.^{[5]}

## Contents

## Basic form[edit]

Suppose *U*_{1} and *U*_{2} are independent samples chosen from the uniform distribution on the unit interval (0, 1). Let

and

Then *Z*_{0} and *Z*_{1} are independent random variables with a standard normal distribution.

The derivation^{[6]} is based on a property of a two-dimensional Cartesian system, where X and Y coordinates are described by two independent and normally distributed random variables, the random variables for *R*^{2} and Θ (shown above) in the corresponding polar coordinates are also independent and can be expressed as

and

Because *R*^{2} is the square of the norm of the standard bivariate normal variable (*X*, *Y*), it has the chi-squared distribution with two degrees of freedom. In the special case of two degrees of freedom, the chi-squared distribution coincides with the exponential distribution, and the equation for *R*^{2} above is a simple way of generating the required exponential variate.

## Polar form[edit]

The polar form was first proposed by J. Bell^{[7]} and then modified by R. Knop.^{[8]} While several different versions of the polar method have been described, the version of R. Knop will be described here because it is the most widely used, in part due to its inclusion in *Numerical Recipes*.

Given *u* and *v*, independent and uniformly distributed in the closed interval [−1, +1], set *s* = *R*^{2} = *u*^{2} + *v*^{2}. If *s* = 0 or *s* ≥ 1, discard *u* and *v*, and try another pair (*u*, *v*). Because *u* and *v* are uniformly distributed and because only points within the unit circle have been admitted, the values of *s* will be uniformly distributed in the open interval (0, 1), too; the latter can be seen by calculating the cumulative distribution function for *s* in the interval (0, 1). This is the area of a circle with radius , divided by . From this we find the probability density function to have the constant value 1 on the interval (0, 1). Equally so, the angle θ divided by is uniformly distributed in the interval [0, 1) and independent of *s*.

We now identify the value of *s* with that of *U*_{1} and with that of *U*_{2} in the basic form. As shown in the figure, the values of and in the basic form can be replaced with the ratios and , respectively. The advantage is that calculating the trigonometric functions directly can be avoided; this is helpful when trigonometric functions are more expensive to compute than the single division that replaces each one.

Just as the basic form produces two standard normal deviates, so does this alternate calculation.

and

## Contrasting the two forms[edit]

The polar method differs from the basic method in that it is a type of rejection sampling, it discards some generated random numbers, but can be faster than the basic method because it is simpler to compute (provided that the random number generator is relatively fast) and is more numerically robust.^{[9]} It avoids the use of trigonometric functions, which can be expensive in some computing environments^{[citation needed]}. It discards 1 − π/4 ≈ 21.46% of the total input uniformly distributed random number pairs generated, i.e. discards 4/π − 1 ≈ 27.32% uniformly distributed random number pairs per Gaussian random number pair generated, requiring 4/π ≈ 1.2732 input random numbers per output random number.

The basic form requires two multiplications, 1/2 logarithm, 1/2 square root, and one trigonometric function for each normal variate.^{[10]} On some processors, the cosine and sine of the same argument can be calculated in parallel using a single instruction. Notably for Intel-based machines, one can use the fsincos assembler instruction or the expi instruction (usually available from C as an intrinsic function), to calculate complex

and just separate the real and imaginary parts.

**Note:**
To explicitly calculate the complex-polar form use the following substitutions in the general form,

Let and Then

The polar form requires 3/2 multiplications, 1/2 logarithm, 1/2 square root, and 1/2 division for each normal variate; the effect is to replace one multiplication and one trigonometric function with a single division and a conditional loop.

## Tails truncation[edit]

When a computer is used to produce a uniform random variable it will inevitably have some inaccuracies because there is a lower bound on how close numbers can be to 0. If the generator uses 32 bits per output value, the smallest non-zero number that can be generated is . When and are equal to this the Box–Muller transform produces a normal random variable equal to This means that the algorithm will not produce random variables more than 6.66 standard deviations from the mean. This corresponds to a proportion of lost due to the truncation.

## Implementation[edit]

The standard Box–Muller transform generates values from the standard normal distribution (*i.e.* standard normal deviates) with mean *0* and standard deviation *1*. The implementation below in standard C++ generates values from any normal distribution with mean and variance . If is a standard normal deviate, then will have a normal distribution with mean and standard deviation . Note that because the random number generator `rand`

has not been seeded, the same series of values will always be returned from the `generateGaussianNoise`

function.

```
#include <cstdlib>
#include <cmath>
#include <limits>
double generateGaussianNoise(double mu, double sigma)
{
static const double epsilon = std::numeric_limits<double>::min();
static const double two_pi = 2.0*3.14159265358979323846;
thread_local double z1;
thread_local bool generate;
generate = !generate;
if (!generate)
return z1 * sigma + mu;
double u1, u2;
do
{
u1 = rand() * (1.0 / RAND_MAX);
u2 = rand() * (1.0 / RAND_MAX);
}
while ( u1 <= epsilon );
double z0;
z0 = sqrt(-2.0 * log(u1)) * cos(two_pi * u2);
z1 = sqrt(-2.0 * log(u1)) * sin(two_pi * u2);
return z0 * sigma + mu;
}
```

## See also[edit]

- Inverse transform sampling
- Marsaglia polar method, similar transform to Box-Muller, which uses Cartesian coordinates, instead of polar coordinates

## References[edit]

- Howes, Lee; Thomas, David (2008).
*GPU Gems 3 - Efficient Random Number Generation and Application Using CUDA*. Pearson Education, Inc. ISBN 978-0-321-51526-1.

**^**Box, G. E. P.; Muller, Mervin E. (1958). "A Note on the Generation of Random Normal Deviates".*The Annals of Mathematical Statistics*.**29**(2): 610–611. doi:10.1214/aoms/1177706645. JSTOR 2237361.**^**Raymond E. A. C. Paley and Norbert Wiener*Fourier Transforms in the Complex Domain,*New York: American Mathematical Society (1934) §37.**^**Kloeden and Platen,*Numerical Solutions of Stochastic Differential Equations*, pp. 11–12**^**Howes & Thomas 2008.**^**Martino, L.; Luengo, D.; Míguez, J. (2012). "Efficient sampling from truncated bivariate Gaussians via Box-Muller transformation".*Electronics Letters*.**48**(24): 1533–1534. CiteSeerX 10.1.1.716.8683. doi:10.1049/el.2012.2816.**^**Sheldon Ross,*A First Course in Probability*, (2002), pp. 279–281**^**Bell, James R. (1968). "Algorithm 334: Normal random deviates".*Communications of the ACM*.**11**(7): 498. doi:10.1145/363397.363547.**^**Knop, R. (1969). "Remark on algorithm 334 [G5]: Normal random deviates".*Communications of the ACM*.**12**(5): 281. doi:10.1145/362946.362996.**^**Everett F. Carter, Jr.,*The Generation and Application of Random Numbers*, Forth Dimensions (1994), Vol. 16, No. 1 & 2.**^**Note that the evaluation of 2π*U*_{1}is counted as one multiplication because the value of 2π can be computed in advance and used repeatedly.