Computational Physics - Department of Physics

(Axel Boer) #1

396 12 Random walks and the Metropolis algorithm


intmain()
{
intmax_trials, number_walks;
doublemove_probability;
// Read in data
initialise(max_trials, number_walks, move_probability) ;
intwalk_cumulative =new int[number_walks+1];
int
walk2_cumulative =new int[number_walks+1];
intprobability =new int[2(number_walks+1)];
for(intwalks = 1; walks <= number_walks; walks++){
walk_cumulative[walks] = walk2_cumulative[walks] = 0;
}
for(intwalks = 0; walks <= 2*number_walks; walks++){
probability[walks] = 0;
}// end initialization of vectors
// Do the mc sampling
mc_sampling(max_trials, number_walks, move_probability,
walk_cumulative, walk2_cumulative, probability);
// Print out results
output(max_trials, number_walks, walk_cumulative,
walk2_cumulative, probability);
delete[] walk_cumulative;// free memory
delete[] walk2_cumulative;delete[] probability;
return0;
}// end main function


The output function contains now the normalization of the probability as well and writes this
to its own file.


voidoutput(intmax_trials,intnumber_walks,
intwalk_cumulative,intwalk2_cumulative,intprobability)
{
ofstream ofile("testwalkers.dat");
ofstream probfile("probability.dat");
for(inti = 1; i <= number_walks; i++){
doublexaverage = walk_cumulative[i]/((double) max_trials);
doublex2average = walk2_cumulative[i]/((double) max_trials);
doublevariance = x2average - xaverage
xaverage;
ofile << setiosflags(ios::showpoint | ios::uppercase);
ofile << setw(6) << i;
ofile << setw(15) << setprecision(8) << xaverage;
ofile << setw(15) << setprecision(8) << variance << endl;
}
ofile.close();
// find norm of probability
doublenorm = 0.;
for(inti = -number_walks; i <= number_walks; i++){
norm += (double) probability[i+number_walks];
}
// write probability
for(inti = -number_walks; i <= number_walks; i++){
doublehistogram = probability[i+number_walks]/norm;
probfile << setiosflags(ios::showpoint | ios::uppercase);
probfile << setw(6) << i;
probfile << setw(15) << setprecision(8) << histogram << endl;
}
probfile.close();
}// end of function output


The sampling part is still done in the same function, but contains now the setup of a histogram
containing the number of times the walker visited a given positionx.

Free download pdf