Computational Physics - Department of Physics

(Axel Boer) #1

12.3 Microscopic Derivation of the Diffusion Equation 387


cin >> max_trials;
cout <<"Number of attempted walks=";
cin >> number_walks;
cout <<"Move probability=";
cin >> move_probability;
}// end of function initialise


voidoutput(intmax_trials,intnumber_walks,
intwalk_cumulative,intwalk2_cumulative)
{
ofstream ofile("testwalkers.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();
}// end of function output


The algorithm is in the functionmc_samplingand tests the probability of moving to the left or
to the right by generating a random number.


voidmc_sampling(intmax_trials,intnumber_walks,
doublemove_probability,intwalk_cumulative,
int
walk2_cumulative)
{
longidum;
idum=-1;// initialise random number generator
for(inttrial=1; trial <= max_trials; trial++){
intposition = 0;
for(intwalks = 1; walks <= number_walks; walks++){
if(ran0(&idum) <= move_probability){
position += 1;
}
else{
position -= 1;
}
walk_cumulative[walks] += position;
walk2_cumulative[walks] += position*position;
}// end of loop over walks
}// end of loop over trials
} // end mc_sampling function


Fig. 12.3 shows that the variance increases linearly as function of the number of time steps, as
expected from the closed-form results. Similarly, the meandisplacement in Fig. 12.4 oscillates
around zero.


12.3 Microscopic Derivation of the Diffusion Equation


When solving partial differential equations such as the diffusion equation numerically, the
derivatives are always discretized. Recalling our discussions from Chapter 3, we can rewrite
the time derivative as

Free download pdf