Computational Physics - Department of Physics

(Axel Boer) #1

11.1 Introduction 347



  • Choose the number of particlesN.

  • Make a loop over time, where the maximum time (or maximum number of steps)
    should be larger than the number of particlesN.

  • For every time step∆tthere is a probabilitynl/Nfor a move to the right. Compare
    this probability with a random numberx.

  • Ifx≤nl/N, decrease the number of particles in the left half by one, i.e.,nl=nl− 1.
    Else, move a particle from the right half to the left, i.e.,nl=nl+ 1.

  • Increase the time by one unit (the external loop).


In this case, a Monte Carlo sample corresponds to one time unit∆t.
The following simple C/C++-program illustrates this model.

http://folk.uio.no/mhjensen/compphys/programs/chapter11/cpp/program2.cpp
// Particles in a box
#include
#include
#include
#include"lib.h"
using namespacestd;


ofstream ofile;
intmain(intargc,charargv[])
{
char
outfilename;
intinitial_n_particles, max_time, time, random_n, nleft;
longidum;
// 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 = 10initial_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;
}

Free download pdf