Morten Hjorth-Jensen Email morten.hjorth-jensen@fys.uio.no, Department of Physics and Center of Mathematics for Applications, University of Oslo and National Superconducting Cyclotron Laboratory, Michigan State University
Date: Fall 2015
First week: intro, MC integration and probability distribution functions (PDFs)
Second week: More on integration, PDFs, MC integration and random walks.
Third week: random walks and statistical physics.
Fourth week: Statistical physics and the Ising and Potts models
Fifth week: Most likely quantum Monte Carlo
Be able to generate random variables following a given probability distribution function PDF
Find a probability distribution function (PDF)
Sampling rule for accepting a move
Compute standard deviation and other expectation values
Techniques for improving errors
Consider the following simple example, namely the tossing of a dice, resulting in the following possible values
These values are called the domain. To this domain we have the corresponding probabilities
The numbers in the domain are the outcomes of the physical process tossing the dice. We cannot tell beforehand whether the outcome is 3 or 5 or any other number in this domain. This defines the randomness of the outcome, or unexpectedness or any other synonimous word which encompasses the uncertitude of the final outcome.
The only thing we can tell beforehand
is that say the outcome 2 has a certain probability.
If our favorite hobby is to spend an hour every evening throwing dice and
registering the sequence of outcomes, we will note that the numbers in the above domain
appear in a random order. After 11 throws the results may look like
Random variables are characterized by a domain which contains all possible values that the random value may take. This domain has a corresponding PDF.
There are two main concepts associated with a stochastic variable. The domain is the set $\mathbb D = \{x\}$ of all accessible values the variable can assume, so that $X \in \mathbb D$. An example of a discrete domain is the set of six different numbers that we may get by throwing of a dice, $x\in\{1,\,2,\,3,\,4,\,5,\,6\}$.
The probability distribution function (PDF) is a function $p(x)$ on the domain which, in the discrete case, gives us the probability or relative frequency with which these values of $X$ occur
In the continuous case, the PDF does not directly depict the actual probability. Instead we define the probability for the stochastic variable to assume any value on an infinitesimal interval around $x$ to be $p(x)dx$. The continuous function $p(x)$ then gives us the density of the probability rather than the probability itself. The probability for a stochastic variable to assume any value on a non-infinitesimal interval $[a,\,b]$ is then just the integral
Qualitatively speaking, a stochastic variable represents the values of numbers chosen as if by chance from some specified PDF so that the selection of a large set of these numbers reproduces this PDF.
Of interest to us is the cumulative probability distribution function (CDF), $P(x)$, which is just the probability for a stochastic variable $X$ to assume any value less than $x$
The relation between a CDF and its corresponding PDF is then
Naturally, it would be nonsensical for any of the values of the domain to occur with a probability greater than $1$ or less than $0$. Also, the PDF must be normalized. That is, all the probabilities must add up to unity. The probability of "anything" to happen is always unity. For both discrete and continuous PDFs, this condition is
with
with mean value $\mu$ and standard deviation $\sigma$. If $\mu=0$ and $\sigma=1$, it is normally called the standard normal distribution
The following simple Python code plots the above distribution for different values of $\mu$ and $\sigma$.
In [2]:
%matplotlib inline
import numpy as np
from math import acos, exp, sqrt
from matplotlib import pyplot as plt
from matplotlib import rc, rcParams
import matplotlib.units as units
import matplotlib.ticker as ticker
rc('text',usetex=True)
rc('font',**{'family':'serif','serif':['Gaussian distribution']})
font = {'family' : 'serif',
'color' : 'darkred',
'weight' : 'normal',
'size' : 16,
}
pi = acos(-1.0)
mu0 = 0.0
sigma0 = 1.0
mu1= 1.0
sigma1 = 2.0
mu2 = 2.0
sigma2 = 4.0
x = np.linspace(-20.0, 20.0)
v0 = np.exp(-(x*x-2*x*mu0+mu0*mu0)/(2*sigma0*sigma0))/sqrt(2*pi*sigma0*sigma0)
v1 = np.exp(-(x*x-2*x*mu1+mu1*mu1)/(2*sigma1*sigma1))/sqrt(2*pi*sigma1*sigma1)
v2 = np.exp(-(x*x-2*x*mu2+mu2*mu2)/(2*sigma2*sigma2))/sqrt(2*pi*sigma2*sigma2)
plt.plot(x, v0, 'b-', x, v1, 'r-', x, v2, 'g-')
plt.title(r'{\bf Gaussian distributions}', fontsize=20)
plt.text(-19, 0.3, r'Parameters: $\mu = 0$, $\sigma = 1$', fontdict=font)
plt.text(-19, 0.18, r'Parameters: $\mu = 1$, $\sigma = 2$', fontdict=font)
plt.text(-19, 0.08, r'Parameters: $\mu = 2$, $\sigma = 4$', fontdict=font)
plt.xlabel(r'$x$',fontsize=20)
plt.ylabel(r'$p(x)$ [MeV]',fontsize=20)
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.savefig('gaussian.pdf', format='pdf')
Whenever the PDF is known implicitly, like in this case, we will drop
the index $X$ for clarity.
A particularly useful class of special expectation values are the
moments. The $n$-th moment of the PDF $p$ is defined as
follows
for a continuous distribution and
for a discrete distribution. Qualitatively it represents the centroid or the average value of the PDF and is therefore simply called the expectation value of $p(x)$.
A special version of the moments is the set of central moments, the n-th central moment defined as
The zero-th and first central moments are both trivial, equal $1$ and $0$, respectively. But the second central moment, known as the variance of $p$, is of particular interest. For the stochastic variable $X$, the variance is denoted as $\sigma^2_X$ or $\mathrm{Var}(X)$
The square root of the variance, $\sigma =\sqrt{\langle (x-\langle x\rangle)^2\rangle}$ is called the standard deviation of $p$. It is the RMS (root-mean-square) value of the deviation of the PDF from its mean value, interpreted qualitatively as the "spread" of $p$ around its mean.
With this definition of a random variable and its associated PDF, we attempt now a clarification of the Monte-Carlo strategy by using the evaluation of an integral as our example.
In discussion on numerical integration we went through standard methods for evaluating an integral like
where $\omega_i$ are the weights determined by the specific integration method
(like Simpson's method) with $x_i$ the given mesh points.
To give you a feeling of how we are to evaluate the above integral using Monte-Carlo,
we employ here the crudest possible approach. Later on we will present
slightly more refined approaches.
This crude approach consists in setting all weights equal 1, $\omega_i=1$. That corresponds to the
rectangle method
where $x_{i-1/2}$ are the midpoint values of $x$. Introducing the concept of the average of the function $f$ for a given PDF $p(x)$ as
and identify $p(x)$ with the uniform distribution, viz $ p(x)=1$ when $x\in [0,1]$ and zero for all other values of $x$. The integral is is then the average of $f$ over the interval $x \in [0,1]$
In addition to the average value $\langle f \rangle$ the other
important quantity in a
Monte-Carlo calculation is the variance $\sigma^2$ and
the standard deviation $\sigma$. We define first the variance
of the integral with $f$ for a uniform distribution in the interval
$x \in [0,1]$ to be
and inserting the uniform distribution this yields
or
The variance is nothing but a measure of the extent to which $f$ deviates from its average over the region of integration. The standard deviation is defined as the square root of the variance. If we consider the above results for a fixed value of $N$ as a measurement, we could recalculate the above average and variance for a series of different measurements. If each such measumerent produces a set of averages for the integral $I$ denoted $\langle f\rangle_l$, we have for $M$ measurements that the integral is given by
We note that the standard deviation is proportional to the inverse square root of the number of measurements
The aim of Monte Carlo calculations is to have $\sigma_N$ as small as possible after $N$ samples. The results from one sample represents, since we are using concepts from statistics, a 'measurement'.
The scaling in the previous equation is clearly unfavorable compared even with the trapezoidal rule. We saw that the trapezoidal rule carries a truncation error
with $h$ the step length. In general, methods based on a Taylor expansion such as the trapezoidal rule or Simpson's rule have a truncation error which goes like $\sim O(h^k)$, with $k \ge 1$. Recalling that the step size is defined as $h=(b-a)/N$, we have an error which goes like
Monte Carlo integration is more efficient in higher dimensions. To see this, let us assume that our integration volume is a hypercube with side $L$ and dimension $d$. This cube contains hence $N=(L/h)^d$ points and therefore the error in the result scales as $N^{-k/d}$ for the traditional methods.
The error in the Monte carlo integration is however independent of $d$ and scales as
Always!
Comparing this error with that of the traditional methods, shows that Monte Carlo integration is more efficient than an algorithm with error in powers of $k$ when
where $\Psi$ is the wave function of the system and $\mathbf{R}_i$ are the coordinates of each particle. If we want to compute the above integral using for example Gaussian quadrature and use for example ten mesh points for the ten particles, we need to compute a ten-dimensional integral with a total of $10^{30}$ mesh points. As an amusing exercise, assume that you have access to today's fastest computer with a theoretical peak capacity of more than one Petaflops, that is $10^{15}$ floating point operations per second. Assume also that every mesh point corresponds to one floating operation per second. Estimate then the time needed to compute this integral with a traditional method like Gaussian quadrature and compare this number with the estimated lifetime of the universe, $T\approx 4.7 \times 10^{17}$s. Do you have the patience to wait?
We end this first part with a discussion of a brute force Monte Carlo program which integrates
where the input is the desired number of Monte Carlo samples.
What we are doing is to employ a random number generator to obtain numbers
$x_i$ in the interval $[0,1]$ through a call to one of the
library functions
$ran0$, $ran1$, $ran2$ or $ran3$ which generate random numbers in the
interval $x\in [0,1]$.
These functions will be discussed in the next section.
Here we simply employ these functions in order
to generate a random variable.
All random number generators produce pseudo-random
numbers in the interval $[0,1]$ using the so-called uniform
probability distribution
$p(x)$ defined as
with $x$ in the interval $x\in [0,1]$.
The present approach to the above integral is often called 'crude' or
'Brute-Force' Monte-Carlo.
Later on in this chapter we will study refinements to this
simple approach. The reason is that a random generator
produces
points that are distributed
in a homogenous way in the interval $[0,1]$.
If our function is peaked around certain values of $x$,
we may end
up sampling function values where
$f(x)$ is small or near zero. Better schemes which reflect the
properties of the function to be integrated are thence needed.
The algorithm is as follows
Choose the number of Monte Carlo samples $N$.
Perform a loop over $N$ and for each step generate a random number $x_i$ in the interval $[0,1]$ through a call to a random number generator.
Use this number to evaluate $f(x_i)$.
Evaluate the contributions to the mean value and the standard deviation for each loop.
After $N$ samples calculate the final mean value and the standard deviation.
#include <iostream>
#include <cmath>
using namespace std;
// Here we define various functions called by the main program
// this function defines the function to integrate
double func(double x);
// Main function begins here
int main()
{
int n;
double MCint, MCintsqr2, fx, Variance;
cout << "Read in the number of Monte-Carlo samples" << endl;
cin >> n;
MCint = MCintsqr2=0.;
double invers_period = 1./RAND_MAX; // initialise the random number generator
srand(time(NULL)); // This produces the so-called seed in MC jargon
// evaluate the integral with the a crude Monte-Carlo method
for ( int i = 1; i <= n; i++){
// obtain a floating number x in [0,1]
double x = double(rand())*invers_period;
fx = func(x);
MCint += fx;
MCintsqr2 += fx*fx;
}
MCint = MCint/((double) n );
MCintsqr2 = MCintsqr2/((double) n );
double variance=MCintsqr2-MCint*MCint;
// final output
cout << " variance= " << variance << " Integral = " << MCint << " Exact= " << M_PI << endl;
} // end of main program
// this function defines the function to integrate
double func(double x)
{
double value;
value = 4/(1.+x*x);
return value;
} // end of function to evaluate
We give here an example of how a system evolves towards a well defined equilibrium state.
Consider a box divided into two equal halves separated by a wall. At the beginning, time $t=0$, there are $N$ particles on the left side. A small hole in the wall is then opened and one particle can pass through the hole per unit time.
After some time the system reaches its equilibrium state with equally many particles in both halves, $N/2$. Instead of determining complicated initial conditions for a system of $N$ particles, we model the system by a simple statistical model. In order to simulate this system, which may consist of $N \gg 1$ particles, we assume that all particles in the left half have equal probabilities of going to the right half. We introduce the label $n_l$ to denote the number of particles at every time on the left side, and $n_r=N-n_l$ for those on the right side.
The probability for a move to the right during a time step $\Delta t$ is $n_l/N$. The algorithm for simulating this problem may then look like this
Choose the number of particles $N$.
Make a loop over time, where the maximum time (or maximum number of steps) should be larger than the number of particles $N$.
For every time step $\Delta t$ there is a probability $n_l/N$ for a move to the right. Compare this probability with a random number $x$.
If $ x \le n_l/N$, decrease the number of particles in the left half by one, i.e., $n_l=n_l-1$. Else, move a particle from the right half to the left, i.e., $n_l=n_l+1$.
Increase the time by one unit (the external loop).
In this case, a Monte Carlo sample corresponds to one time unit $\Delta t$.
The following simple C/C++-program illustrates this model.
// Particles in a box
#include <iostream>
#include <fstream>
#include <iomanip>
#include "lib.h"
using namespace std;
ofstream ofile;
int main(int argc, char* argv[])
{
char *outfilename;
int initial_n_particles, max_time, time, random_n, nleft;
long idum;
// Read in output file, abort if there are too few command-line arguments
if( argc <= 1 ){
cout << "Bad Usage: " << argv[0] <<
" read also output file on same line" << endl;
exit(1);
}
else{
outfilename=argv[1];
}
ofile.open(outfilename);
// Read in data
cout << "Initial number of particles = " << endl ;
cin >> initial_n_particles;
// setup of initial conditions
nleft = initial_n_particles;
max_time = 10*initial_n_particles;
idum = -1;
// sampling over number of particles
for( time=0; time <= max_time; time++){
random_n = ((int) initial_n_particles*ran0(&idum));
if ( random_n <= nleft){
nleft -= 1;
}
else{
nleft += 1;
}
ofile << setiosflags(ios::showpoint | ios::uppercase);
ofile << setw(15) << time;
ofile << setw(15) << nleft << endl;
}
return 0;
} // end main function
and assuming that $n_l$ and $t$ are continuous variables we arrive at
whose solution is
with the initial condition $n_l(t=0)=N$. Note that we have assumed $n$ to be a continuous variable. Obviously, particles are discrete objects.
In essence the Monte Carlo method contains the following ingredients
A PDF which characterizes the system
Random numbers which are generated so as to cover in an as uniform as possible way on the unity interval [0,1].
A sampling rule
An error estimation
Techniques for improving the errors
The following table collects properties of probability distribution functions. In our notation we reserve the label $p(x)$ for the probability of a certain event, while $P(x)$ is the cumulative probability.
Discrete PDF | Continuous PDF | |
---|---|---|
Domain | $\left\{x_1, x_2, x_3, \dots, x_N\right\}$ | $[a,b]$ |
Probability | $p(x_i)$ | $p(x)dx$ |
Cumulative | $P_i=\sum_{l=1}^ip(x_l)$ | $P(x)=\int_a^xp(t)dt$ |
Positivity | $ 0 \le p(x_i) \le 1$ | $ p(x) \ge 0$ |
Positivity | $ 0 \le P_i \le 1$ | $ 0 \le P(x) \le 1$ |
Monotonic | $P_i \ge P_j$ if $x_i \ge x_j$ | $P(x_i) \ge P(x_j)$ if $x_i \ge x_j$ |
Normalization | $P_N=1$ | $P(b)=1$ |
With a PDF we can compute expectation values of selected quantities such as
if we have a discrete PDF or
yielding probabilities different from zero in the interval $[a,b]$.
The exponential distribution
yielding probabilities different from zero in the interval $[0,\infty)$ and with mean value
with variance
with probabilities different from zero in the interval $(-\infty,\infty)$. The integral $\int_{-\infty}^{\infty}\exp{\left(-(x^2\right)}dx$ appears in many calculations, its value is $\sqrt{\pi}$, a result we will need when we compute the mean value and the variance. The mean value is
which becomes with a suitable change of variables
and inserting the mean value and performing a variable change we obtain
and performing a final integration by parts we obtain the well-known result $\sigma^2=b^2$. It is useful to introduce the standard normal distribution as well, defined by $\mu=a=0$, viz. a distribution centered around zero and with a variance $\sigma^2=1$, leading to
where $y$ is the probability for a specific event, such as the tossing of a coin or moving left or right in case of a random walker. Note that $x$ is a discrete stochastic variable.
The sequence of binomial trials is characterized by the following definitions
Every experiment is thought to consist of $N$ independent trials.
In every independent trial one registers if a specific situation happens or not, such as the jump to the left or right of a random walker.
The probability for every outcome in a single trial has the same value, for example the outcome of tossing (either heads or tails) a coin is always $1/2$.
In order to compute the mean and variance we need to recall Newton's binomial formula
which can be used to show that
the PDF is normalized to one. The mean value is
resulting in
which we rewrite as
In this case both the mean value and the variance are easier to calculate,
and the variance is $\sigma^2=\lambda$.
An example of applications of the Poisson distribution could be the counting of the number of $\alpha$-particles emitted from a radioactive source in a given time interval. In the limit of $n\rightarrow \infty$ and for small probabilities $y$, the binomial distribution approaches the Poisson distribution. Setting $\lambda = ny$, with $y$ the probability for an event in the binomial distribution we can show that
An important quantity in a statistical analysis is the so-called covariance.
Consider the set $\{X_i\}$ of $n$ stochastic variables (not necessarily uncorrelated) with the multivariate PDF $P(x_1,\dots,x_n)$. The covariance of two of the stochastic variables, $X_i$ and $X_j$, is defined as follows
with
then the diagonal elements are just the familiar variances, $C_{ii} = \mathrm{Cov}(X_i,\,X_i) = \mathrm{Var}(X_i)$. It turns out that all the off-diagonal elements are zero if the stochastic variables are uncorrelated.
This is easy to show, keeping in mind the linearity of the expectation value. Consider the stochastic variables $X_i$ and $X_j$, ($i\neq j$)
If $X_i$ and $X_j$ are independent, we get
Now that we have constructed an idealized mathematical framework, let us try to apply it to empirical observations. Examples of relevant physical phenomena may be spontaneous decays of nuclei, or a purely mathematical set of numbers produced by some deterministic mechanism. It is the latter we will deal with, using so-called pseudo-random number generators. In general our observations will contain only a limited set of observables. We remind the reader that a stochastic process is a process that produces sequentially a chain of values
We will call these values our measurements and the entire set as our measured sample. The action of measuring all the elements of a sample we will call a stochastic experiment (since, operationally, they are often associated with results of empirical observation of some physical or mathematical phenomena; precisely an experiment). We assume that these values are distributed according to some PDF $p_X^{\phantom X}(x)$, where $X$ is just the formal symbol for the stochastic variable whose PDF is $p_X^{\phantom X}(x)$. Instead of trying to determine the full distribution $p$ we are often only interested in finding the few lowest moments, like the mean $\mu_X^{\phantom X}$ and the variance $\sigma_X^{\phantom X}$.
In practical situations however, a sample is always of finite size. Let that size be $n$. The expectation value of a sample $\alpha$, the sample mean, is then defined as follows
The sample variance is:
with its square root being the standard deviation of the sample.
You can think of the above observables as a set of quantities which define a given experiment. This experiment is then repeated several times, say $m$ times. The total average is then
where the last sums end at $m$ and $n$. The total variance is
which we rewrite as
These quantities, being known experimental values or the results from our calculations, may differ, in some cases significantly, from the similarly named exact values for the mean value $\mu_X$, the variance $\mathrm{Var}(X)$ and the covariance $\mathrm{Cov}(X,Y)$.
The central limit theorem states that the PDF $\tilde{p}(z)$ of the average of $m$ random values corresponding to a PDF $p(x)$ is a normal distribution whose mean is the mean value of the PDF $p(x)$ and whose variance is the variance of the PDF $p(x)$ divided by $m$, the number of values used to compute $z$.
The central limit theorem leads then to the well-known expression for the standard deviation, given by
In many cases the above estimate for the standard deviation, in particular if correlations are strong, may be too simplistic. We need therefore a more precise defintion of the error and the variance in our results.
Our estimate of the true average $\mu_{X}$ is the sample mean $\langle X_m \rangle$
We can then use Eq. (9)
and rewrite it as
where the first term is the sample variance of all $mn$ experiments divided by $n$ and the last term is nothing but the covariance which arises when $k\ne l$.
Our estimate of the true average $\mu_{X}$ is the sample mean $\langle X_m \rangle$
If the observables are uncorrelated, then the covariance is zero and we obtain a total variance which agrees with the central limit theorem. Correlations may often be present in our data set, resulting in a non-zero covariance. The first term is normally called the uncorrelated contribution. Computationally the uncorrelated first term is much easier to treat efficiently than the second. We just accumulate separately the values $x^2$ and $x$ for every measurement $x$ we receive. The correlation term, though, has to be calculated at the end of the experiment since we need all the measurements to calculate the cross terms. Therefore, all measurements have to be stored throughout the experiment.
Let us analyze the problem by splitting up the correlation term into partial sums of the form
The correlation term of the total variance can now be rewritten in terms of $f_d$
The value of $f_d$ reflects the correlation between measurements separated by the distance $d$ in the samples. Notice that for $d=0$, $f$ is just the sample variance, $\sigma^2$. If we divide $f_d$ by $\sigma^2$, we arrive at the so called autocorrelation function
and we see that $\sigma_m$ can be expressed in terms of the uncorrelated sample variance times a correction factor $\tau$ which accounts for the correlation between measurements. We call this correction factor the autocorrelation time
For a correlation free experiment, $\tau$ equals 1.
From the point of view of Eq. (12) we can interpret a sequential correlation as an effective reduction of the number of measurements by a factor $\tau$. The effective number of measurements becomes
To neglect the autocorrelation time $\tau$ will always cause our simple uncorrelated estimate of $\sigma_m^2\approx \sigma^2/n$ to be less than the true sample error. The estimate of the error will be too "good". On the other hand, the calculation of the full autocorrelation time poses an efficiency problem if the set of measurements is very large. The solution to this problem is given by more practically oriented methods like the blocking technique.
Uniform deviates are just random numbers that lie within a specified range (typically 0 to 1), with any one number in the range just as likely as any other. They are, in other words, what you probably think random numbers are. However, we want to distinguish uniform deviates from other sorts of random numbers, for example numbers drawn from a normal (Gaussian) distribution of specified mean and standard deviation. These other sorts of deviates are almost always generated by performing appropriate operations on one or more uniform deviates, as we will see in subsequent sections. So, a reliable source of random uniform deviates, the subject of this section, is an essential building block for any sort of stochastic modeling or Monte Carlo computer work.
A disclaimer is however appropriate. It should be fairly obvious that something as deterministic as a computer cannot generate purely random numbers.
Numbers generated by any of the standard algorithms are in reality pseudo random numbers, hopefully abiding to the following criteria:
they produce a uniform distribution in the interval [0,1].
correlations between random numbers are negligible
the period before the same sequence of random numbers is repeated is as large as possible and finally
the algorithm should be fast.
The most common random number generators are based on so-called Linear congruential relations of the type
which yield a number in the interval [0,1] through
The number $M$ is called the period and it should be as large as possible and $N_0$ is the starting value, or seed. The function $\mathrm{MOD}$ means the remainder, that is if we were to evaluate $(13)\mathrm{MOD}(9)$, the outcome is the remainder of the division $13/9$, namely $4$.
The problem with such generators is that their outputs are periodic; they will start to repeat themselves with a period that is at most $M$. If however the parameters $a$ and $c$ are badly chosen, the period may be even shorter.
Consider the following example
with a seed $N_0=2$. This generator produces the sequence $4,1,3,0,2,4,1,3,0,2,...\dots$, i.e., a sequence with period $5$. However, increasing $M$ may not guarantee a larger period as the following example shows
which still, with $N_0=2$, results in $11,38,11,38,11,38,\dots$, a period of just $2$.
Typical periods for the random generators provided in the program library are of the order of $\sim 10^9$ or larger. Other random number generators which have become increasingly popular are so-called shift-register generators. In these generators each successive number depends on many preceding values (rather than the last values as in the linear congruential generator). For example, you could make a shift register generator whose $l$th number is the sum of the $l-i$th and $l-j$th values with modulo $M$,
Such a generator again produces a sequence of pseudorandom numbers but this time with a period much larger than $M$. It is also possible to construct more elaborate algorithms by including more than two past terms in the sum of each iteration. One example is the generator of Marsaglia and Zaman which consists of two congruential relations
followed by
where the bitwise action of $\oplus$ means that if $N_{l-i}=N_{l-j}$ the result is $0$ whereas if $N_{l-i}\ne N_{l-j}$ the result is $1$. As an example, consider the case where $N_{l-i}=6$ and $N_{l-j}=11$. The first one has a bit representation (using 4 bits only) which reads $0110$ whereas the second number is $1011$. Employing the $\oplus$ operator yields $1101$, or $2^3+2^2+2^0=13$.
In Fortran90, the bitwise $\oplus$ operation is coded through the intrinsic function $\mathrm{IEOR}(m,n)$ where $m$ and $n$ are the input numbers, while in $C$ it is given by $m\wedge n$.
We show here how the linear congruential algorithm can be implemented, namely
However, since $a$ and $N_{i-1}$ are integers and their multiplication could become greater than the standard 32 bit integer, there is a trick via Schrage's algorithm which approximates the multiplication of large integers through the factorization
where we have defined
and
since we can add or subtract any integer multiple of $M$ from $aN_{i-1}$. The last term $ [N_{i-1}/q]M \mathrm{MOD} (M)$ is zero since the integer division $[N_{i-1}/q]$ just yields a constant which is multiplied with $M$.
We can now rewrite Eq. (16) as
which results in
yielding
The term $[N_{i-1}/q]r$ is always smaller or equal $N_{i-1}(r/q)$ and with $r < q$ we obtain always a number smaller than $N_{i-1}$, which is smaller than $M$. And since the number $N_{i-1}\mathrm{MOD} (q)$ is between zero and $q-1$ then $a(N_{i-1}\mathrm{MOD} (q))< aq$. Combined with our definition of $q=[M/a]$ ensures that this term is also smaller than $M$ meaning that both terms fit into a 32-bit signed integer. None of these two terms can be negative, but their difference could. The algorithm below adds $M$ if their difference is negative. Note that the program uses the bitwise $\oplus$ operator to generate the starting point for each generation of a random number. The period of $ran0$ is $\sim 2.1\times 10^{9}$. A special feature of this algorithm is that is should never be called with the initial seed set to $0$.
/*
** The function
** ran0()
** is an "Minimal" random number generator of Park and Miller
** Set or reset the input value
** idum to any integer value (except the unlikely value MASK)
** to initialize the sequence; idum must not be altered between
** calls for sucessive deviates in a sequence.
** The function returns a uniform deviate between 0.0 and 1.0.
*/
double ran0(long &idum)
{
const int a = 16807, m = 2147483647, q = 127773;
const int r = 2836, MASK = 123459876;
const double am = 1./m;
long k;
double ans;
idum ^= MASK;
k = (*idum)/q;
idum = a*(idum - k*q) - r*k;
// add m if negative difference
if(idum < 0) idum += m;
ans=am*(idum);
idum ^= MASK;
return ans;
} // End: function ran0()
As mentioned previously, the underlying PDF for the generation of random numbers is the uniform distribution, meaning that the probability for finding a number $x$ in the interval [0,1] is $p(x)=1$.
A random number generator should produce numbers which are uniformly distributed in this interval. The table shows the distribution of $N=10000$ random numbers generated by the functions in the program library. We note in this table that the number of points in the various intervals $0.0-0.1$, $0.1-0.2$ etc are fairly close to $1000$, with some minor deviations.
Two additional measures are the standard deviation $\sigma$ and the mean $\mu=\langle x\rangle$.
For the uniform distribution, the mean value $\mu$ is then
while the standard deviation is
The various random number generators produce results which agree rather well with these limiting values.
$x$-bin | ran0 | ran1 | ran2 | ran3 |
---|---|---|---|---|
0.0-0.1 | 1013 | 991 | 938 | 1047 |
0.1-0.2 | 1002 | 1009 | 1040 | 1030 |
0.2-0.3 | 989 | 999 | 1030 | 993 |
0.3-0.4 | 939 | 960 | 1023 | 937 |
0.4-0.5 | 1038 | 1001 | 1002 | 992 |
0.5-0.6 | 1037 | 1047 | 1009 | 1009 |
0.6-0.7 | 1005 | 989 | 1003 | 989 |
0.7-0.8 | 986 | 962 | 985 | 954 |
0.8-0.9 | 1000 | 1027 | 1009 | 1023 |
0.9-1.0 | 991 | 1015 | 961 | 1026 |
$\mu$ | 0.4997 | 0.5018 | 0.4992 | 0.4990 |
$\sigma$ | 0.2882 | 0.2892 | 0.2861 | 0.2915 |
Since our random numbers, which are typically generated via a linear congruential algorithm,
are never fully independent, we can then define
an important test which measures the degree of correlation, namely the so-called
auto-correlation function defined previously, see again Eq. (11).
We rewrite it here as
with $C_0=1$. Recall that $\sigma^2=\langle x_i^2\rangle-\langle x_i\rangle^2$. The non-vanishing of $C_k$ for $k\ne 0$ means that the random numbers are not independent. The independence of the random numbers is crucial in the evaluation of other expectation values. If they are not independent, our assumption for approximating $\sigma_N$ in Eq. (3) is no longer valid.
We have presented a simple brute force approach to integration with the Monte Carlo method. There we sampled over a given number of points distributed uniformly in the interval $[0,1]$
with $p(x)=1$ and satisfying
which for the uniform distribution implies
Let us assume that $p(y)$ is a PDF different from the uniform PDF $p(x)=1$ with $x \in [0,1]$. If we integrate the last expression we arrive at
which is nothing but the cumulative distribution of $p(y)$, i.e.,
If we wish to relate this distribution to the one in the interval $x \in [0,1]$ we have
and integrating we obtain the cumulative function
yielding
which is the exponential distribution, important for the analysis of e.g., radioactive decay. Again, $p(x)$ is given by the uniform distribution with $x \in [0,1]$, and with the assumption that the probability is conserved we have
which yields after integration
or
which we rewrite as
where $x_i$ is a random number in the interval $[0,1]$.
We have changed the integration limits in the second integral, since we have performed a change of variables. Since we have used the uniform distribution defined for $x\in [0,1]$, the integration limits change to $0$ and $1$. The variable $y$ is now a function of $x$. Note also that in practical implementations, our random number generators for the uniform distribution never return exactly 0 or 1, but we may come very close.
The algorithm for the last example is rather simple. In the function which sets up the integral, we simply need to call one of the random number generators like $ran0$, $ran1$, $ran2$ or $ran3$ in order to obtain numbers in the interval [0,1]. We obtain $y$ by the taking the logarithm of $(1-x)$. Our calling function which sets up the new random variable $y$ may then include statements like
.....
idum=-1;
x=ran0(&idum);
y=-log(1.-x);
.....
it is rather difficult to find an inverse since the cumulative distribution is given by the error function $erf(x)$ % add reference
resulting in
where the angle $\theta$ could be given by a uniform distribution in the region $[0,2\pi]$. Following example 1 above, this implies simply multiplying random numbers $x\in [0,1]$ by $2\pi$.
The variable $r$, defined for $r \in [0,\infty)$ needs to be related to to random numbers $x'\in [0,1]$. To achieve that, we introduce a new variable
and define a PDF
with $u\in [0,\infty)$. Using the results from example 2 for the exponential distribution, we have
and
we can obtain new random numbers $x,y$ through
and
.....
idum=-1;
radius=sqrt(-2*ln(1.-ran0(idum)));
theta=2*pi*ran0(idum);
x=radius*cos(theta);
y=radius*sin(theta);
.....
With the aid of the above variable transformations we address now one of the most widely used approaches to Monte Carlo integration, namely importance sampling.
Let us assume that $p(y)$ is a PDF whose behavior resembles that of a function $F$ defined in a certain interval $[a,b]$. The normalization condition is
We can rewrite our integral as
where we used
If we can invert $x(y)$, we find $y(x)$ as well.
With this change of variables we can express the integral of Eq. (20) as
meaning that a Monte Carlo evaluation of the above integral gives
Note the change in integration limits from $a$ and $b$ to $\tilde{a}$ and $\tilde{b}$. The advantage of such a change of variables in case $p(y)$ follows closely $F$ is that the integrand becomes smooth and we can sample over relevant values for the integrand. It is however not trivial to find such a function $p$. The conditions on $p$ which allow us to perform these transformations are
$p$ is normalizable and positive definite,
it is analytically integrable and
the integral is invertible, allowing us thereby to express a new variable in terms of the old one.
The variance is now with the definition
given by
by rewriting
since
with $y_i\in [0,1]$,
This is a rather simple and appealing method after von Neumann. Assume that we are looking at an interval $x\in [a,b]$, this being the domain of the PDF $p(x)$. Suppose also that the largest value our distribution function takes in this interval is $M$, that is
Then we generate a random number $x$ from the uniform distribution for $x\in [a,b]$ and a corresponding number $s$ for the uniform distribution between $[0,M]$. If
Obviously to derive a closed-form expression is much easier, however the integrand could pose some more difficult challenges. The aim here is simply to show how to implent the acceptance-rejection algorithm. The integral is the area below the curve $f(x)=\exp{(x)}$. If we uniformly fill the rectangle spanned by $x\in [0,3]$ and $y\in [0,\exp{(3)}]$, the fraction below the curve obtained from a uniform distribution, and multiplied by the area of the rectangle, should approximate the chosen integral.
It is rather easy to implement this numerically, as shown in the following code.
// Loop over Monte Carlo trials n
integral =0.;
for ( int i = 1; i <= n; i++){
// Finds a random value for x in the interval [0,3]
x = 3*ran0(&idum);
// Finds y-value between [0,exp(3)]
y = exp(3.0)*ran0(&idum);
// if the value of y at exp(x) is below the curve, we accept
if ( y < exp(x)) s = s+ 1.0;
// The integral is area enclosed below the line f(x)=exp(x)
}
// Then we multiply with the area of the rectangle and divide by the number of cycles
Integral = 3.*exp(3.)*s/n
with $x_i$ defined in the interval $[a_i,b_i]$ we would typically need a transformation of variables of the form
and to convert the function $g(x_1,\dots,x_d)$ to
where
with $d=6$.
We can solve this integral by employing our brute force scheme, or using importance sampling and random variables distributed according to a gaussian PDF. For the latter, if we set the mean value $\mu=0$ and the standard deviation $\sigma=1/\sqrt{2}$, we have
and using this normal distribution we rewrite our integral as
where $f$ is the above normal distribution and
#include <iostream>
#include <fstream>
#include <iomanip>
#include "lib.h"
using namespace std;
double brute_force_MC(double *);
// Main function begins here
int main()
{
int n;
double x[6], y, fx;
double int_mc = 0.; double variance = 0.;
double sum_sigma= 0. ; long idum=-1 ;
double length = 5.; // we fix the max size of the box to L=5
double jacobidet = pow((2*length),6);
cout << "Read in the number of Monte-Carlo samples" << endl;
cin >> n;
// evaluate the integral with importance sampling
for ( int i = 1; i <= n; i++){
// x[] contains the random numbers for all dimensions
for (int j = 0; j< 6; j++) {
x[j]=-length+2*length*ran0(&idum);
}
fx=brute_force_MC(x);
int_mc += fx;
sum_sigma += fx*fx;
}
int_mc = int_mc/((double) n );
sum_sigma = sum_sigma/((double) n );
variance=sum_sigma-int_mc*int_mc;
// final output
cout << setiosflags(ios::showpoint | ios::uppercase);
cout << " Monte carlo result= " << setw(10) << setprecision(8) << jacobidet*int_mc;
cout << " Sigma= " << setw(10) << setprecision(8) << volume*sqrt(variance/((double) n )) << endl;
return 0;
} // end of main program
// this function defines the integrand to integrate
double brute_force_MC(double *x)
{
// evaluate the different terms of the exponential
double xx=x[0]*x[0]+x[1]*x[1]+x[2]*x[2];
double yy=x[3]*x[3]+x[4]*x[4]+x[5]*x[5];
double xy=pow((x[0]-x[3]),2)+pow((x[1]-x[4]),2)+pow((x[2]-x[5]),2);
return exp(-xx-yy)*xy;
} // end function for the integrand
// importance sampling with gaussian deviates
#include <iostream>
#include <fstream>
#include <iomanip>
#include "lib.h"
using namespace std;
double gaussian_MC(double *);
double gaussian_deviate(long *);
// Main function begins here
int main()
{
int n;
double x[6], y, fx;
cout << "Read in the number of Monte-Carlo samples" << endl;
cin >> n;
double int_mc = 0.; double variance = 0.;
double sum_sigma= 0. ; long idum=-1 ;
double jacobidet = pow(acos(-1.),3.);
double sqrt2 = 1./sqrt(2.);
// evaluate the integral with importance sampling
for ( int i = 1; i <= n; i++){
// x[] contains the random numbers for all dimensions
for (int j = 0; j < 6; j++) {
x[j] = gaussian_deviate(&idum)*sqrt2;
}
fx=gaussian_MC(x);
int_mc += fx;
sum_sigma += fx*fx;
}
int_mc = int_mc/((double) n );
sum_sigma = sum_sigma/((double) n );
variance=sum_sigma-int_mc*int_mc;
// final output
cout << setiosflags(ios::showpoint | ios::uppercase);
cout << " Monte carlo result= " << setw(10) << setprecision(8) << jacobidet*int_mc;
cout << " Sigma= " << setw(10) << setprecision(8) << volume*sqrt(variance/((double) n )) << endl;
return 0;
} // end of main program
// this function defines the integrand to integrate
double gaussian_MC(double *x)
{
// evaluate the different terms of the exponential
double xy=pow((x[0]-x[3]),2)+pow((x[1]-x[4]),2)+pow((x[2]-x[5]),2);
return xy;
} // end function for the integrand
// random numbers with gaussian distribution
double gaussian_deviate(long * idum)
{
static int iset = 0;
static double gset;
double fac, rsq, v1, v2;
if ( idum < 0) iset =0;
if (iset == 0) {
do {
v1 = 2.*ran0(idum) -1.0;
v2 = 2.*ran0(idum) -1.0;
rsq = v1*v1+v2*v2;
} while (rsq >= 1.0 || rsq == 0.);
fac = sqrt(-2.*log(rsq)/rsq);
gset = v1*fac;
iset = 1;
return v2*fac;
} else {
iset =0;
return gset;
}
} // end function for gaussian deviates
The following table lists the results from the above two programs as function of the number of Monte Carlo samples. The suffix $cr$ stands for the brute force approach while $gd$ stands for the use of a Gaussian distribution function. One sees clearly that the approachwith a Gaussian distribution function yields a much improved numerical result, with fewer samples.
$N$ | $I_{cr}$ | $I_{gd}$ |
---|---|---|
10000 | 9.92072E+01 | 9.33225E+01 |
100000 | 8.75039E+01 | 9.30042E+01 |
1000000 | 9.56759E+01 | 9.29988E+01 |
10000000 | 9.15446E+01 | 9.30203E+01 |