Friday, August 27, 2010

Pi Estimation using Monte Carlo Method in C++ (Visual C++)


Here is C++ implementation of Pi Estimation using Monte Carlo Method.

Generating a uniformly distributed random number in C++ was quite a task. I think it's better to use a well-made library for random number generation. (e.g. Boost library)

a. header file

public class PiEstimator {
public:
PiEstimator(void);
~PiEstimator(void);
double estimatePi(int numIter);
};


b. cpp implementation file

#include "PiEstimator.h"
#include
#include
#include

unsigned time_seed() {
time_t now = time ( NULL );
unsigned char *p = (unsigned char *)&now;
unsigned seed = 0;
size_t i;

for ( i = 0; i < sizeof now; i++ )
seed = seed * ( UCHAR_MAX + 2U ) + p[i];

return seed;
}

PiEstimator::PiEstimator(void) {
srand ((unsigned)time_seed());
}

PiEstimator::~PiEstimator(void) {
}

double randomNumber() {
return (double)rand()/(double)RAND_MAX;
}

double getRandDistance() {
double x = randomNumber();
double y = randomNumber();
return sqrt(pow(x,2) + pow(y,2));
}

double PiEstimator::estimatePi(int numIter) {
int numHits = 0;
for (int i = 0; i < numIter; i++) {
if (getRandDistance() <= 1) {
numHits++;
}
}
double pi = 4 * (numHits / (double)numIter);
return pi;
}

No comments: