Next: Extra Tasks Up: Monte-Carlo Class How To Previous: Stage 1 - Make

## Stage 2 - Use a vector for the random numbers

Copy the code below (or using your code from last time) to a new project (or file) and call it `monte-carlo-3'. It is a good idea to keep a copy of any working code so that you can go back to it at any stage and start again.

Now let us add a vector for random numbers. At the moment we throw away half of the random numbers that we generate, so use a vector (length=N) to store the random numbers. We shall need a class that returns a vector of random numbers rather than a single value. Example use of such a class would be:

vector< double> phi;
phi = RandomND(N);
sum = 0.;
for( int i=0;i<phi.size();i++)sum+=phi[i];
mean = sum/phi.size()

Now delete the function phi in your program, we are going to replace it with a class. Remember to include the vector library at the top of your program.

class RandomND
{
public:
// global const for Pi
static const double Pi;
// overload the () operator and allow the user to specify
// the required size of the random number vector
vector< double> operator ()( int N)
{
// make sure N is even
if(N%2==1)N+=1;
// make a vector size N
vector< double> temp_vec(N);
double x1,x2;
int temp1,temp2,i;
// i is the number of random number currently calculated
i = 0;
do
{
temp1 = rand();
temp2 = rand();
// if temp1 or temp2 = 0 then continue back to the start of the
// loop and don't use these numbers
if(temp1==0 || temp2==0)continue;
x1 = double(temp1)/RAND_MAX;
x2 = double(temp2)/RAND_MAX;
// add two box muller numbers to the vector
temp_vec[i]=   // box muller method in here
temp_vec[i+1]=   // box muller method in here
i+=2;
// when i==N then exit
}while(i<N);
return temp_vec;
};
// name a default instance of the class RandomND
}RandomND;
// initialise the value of Pi
const double RandomND::Pi=atan(1.0)*4.0;

You need to fill in the expression for the box-muller method. Now we have a class (and default instance) that will return a vector of random normally distributed numbers, we just need to include this in our MonteCarlo class. The next steps are:

• declare a vector called phi inside the MonteCarlo class;
• inside the function monte_carlo assign the vector phi to be equal to a vector of random numbers, using the RandomND class;
• inside monte_carlo, change the function call phi() to get a number from the vector phi.

Subsections

Next: Extra Tasks Up: Monte-Carlo Class How To Previous: Stage 1 - Make
Paul Johnson 2009-04-06