Computational Physics - Department of Physics

(Axel Boer) #1

11.1 Introduction 345



  • Choose the number of Monte Carlo samplesN.

  • Perform a loop overNand for each step generate a a random numberxiin the interval
    [ 0 , 1 ]through a call to a random number generator.

  • Use this number to evaluatef(xi).

  • Evaluate the contributions to the mean value and the standard deviation for each
    loop.

  • AfterNsamples calculate the final mean value and the standard deviation.


The following C/C++ program^2 implements the above algorithm using the library function
ran 0 to computeπ. Note again the inclusion of thelib.hfile which has the random number
generator functionran0.


http://folk.uio.no/mhjensen/compphys/programs/chapter11/cpp/program1.cpp
#include
#include"lib.h"
using namespacestd;


// Here we define various functions called by the main program
// this function defines the function to integrate


doublefunc(doublex);


// Main function begins here
intmain()
{
inti, n;
longidum;
doublecrude_mc, x, sum_sigma, fx, variance;
cout <<"Read in the number of Monte-Carlo samples"<< endl;
cin >> n;
crude_mc = sum_sigma=0. ; idum=-1 ;
// evaluate the integral with the a crude Monte-Carlo method
for( i = 1; i <= n; i++){
x=ran0(&idum);
fx=func(x);
crude_mc += fx;
sum_sigma += fxfx;
}
crude_mc = crude_mc/((double) n );
sum_sigma = sum_sigma/((double) n );
variance=sum_sigma-crude_mc
crude_mc;


// final output
cout <<" variance= "<< variance <<" Integral = "
<< crude_mc <<" Exact= "<< M_PI << endl;
}// end of main program
// this function defines the function to integrate
doublefunc(doublex)
{
doublevalue;
value = 4/(1.+x*x);
returnvalue;
}// end of function to evaluate


(^2) The Fortran 90/95 programs are not listed in the main text, they are found under the corresponding chapter
as programs/chapter8/programn.f90.

Free download pdf