Integration and sampling:

from the Gaussian integral to the Maxwell-Boltzmann distribution

In this lecture, we relate the concepts of sampling and of integration. The connection between the two was not clearly brought out before. We then treat general methods for directly sampling non-uniform distributions. A number of very detailed texts have been written on the subject, see for example[1] .

Sample transformation: The example of Gaussian random numbers

Going up and down in the Gaussian integral

As an illustration of how sampling relates to integration, we consider the Gaussian integral:

As we learned many years ago, we square this integral, write it down once in x and once in y:

and then switch to polar coordinates

to reach the following expression for the integral

We may then perform the substitutions

to reach

In this last equation, we can compute the integrals (thus giving the value of the Gaussian integral), but we may in particular sample them: <math>\phi</math> is a uniform random variable between 0 and 2 \pi and \Psi is a uniform random variable between 0 and 1. In the below program, we actually sample the random variables \phi and \Psi , and transform these samples in several steps back to x and y. This procedure carries the name of "sample transformation".

Python program for the Gaussian sample transformation

Note that the substitutions are applied to the samples phi and Psi. This is also known as the Box-Muller transform.
from random import uniform
import math
import pylab
def gauss(sigma):
    phi = uniform(0.0, 2.0 * math.pi)
    Psi = uniform(0.0, 1.0)
    Upsilon = - math.log(Psi)
    r = sigma * math.sqrt(2.0 * Upsilon)
    x = r * math.cos(phi)
    y = r * math.sin(phi)
    return x, y
listx = []; listy = []
for k in range(10000):
    x, y = gauss(1.0)
list = listx + listy
pylab.hist(list, bins=25, normed=True)
pylab.title('Histogram Gaussian')
pylab.title('Correlation x,y')

Output of the above Python program

Here, we check that the correlations between x and y vanish.
Multi-dimensional Gaussians and the Maxwell distribution (theoretical treatment)
from mpl_toolkits.mplot3d import Axes3D
import pylab, random, math
ax = pylab.gca(projection='3d')
x, y, z = [], [], []
for i in range(2000):
    a, b, c = random.gauss(0.0, 1.0), random.gauss(0.0, 1.0), random.gauss(0.0, 1.0)
    length = math.sqrt(a ** 2 + b ** 2 + c ** 2)
    x.append(a / length)
    y.append(b / length)
    z.append(c / length)
pylab.plot(x, y, z, '.')

Output of the above Python program. Three rescaled Gaussians yield an isotropic distribution in space. Download the program to generate a figure that you can look at from different angles, using your computer mouse.


  1. ^ L. Devroye, Non-Uniform Random Variate Generation Springer 1986, p. 107 for the pdf of the entire book