Probably the code below is not the best looking, but it gets the job done. At least that is what I thought. I encounter a problem when I try to use a number of sample points that is bigger than 250,0000. I do not really know how to go about this.
The only thing that I have tried was switching the type of the variable from int to long.
double MonteCarlo(){
const long N = 250000;
double GenR[NumPoints],apprx;
static double result[1];
double sum = 0;
default_random_engine generator;
uniform_real_distribution<double> distribution(0.0,1.0);
for(int i=0; i<=NumPoints; i++){
randGen[i] = distribution(generator);
sum += 4*exp(16*pow(GenR[i],2)-12*GenR[i]+2);
}
apprx = sum/NumPoints;
return apprx;
}
A double
is 8 bytes. 250K of those things is 2MB. You've very likely exceeded the available stack size. There are compiler options and run time calls that can increase the amount of stack space per thread, but ideally you just allocate that many items off the heap instead of taking a large stack allocation. That is instead of this:
double GenR[NumPoints];
This:
double* GenR = new double[NumPoints];
. . .
delete [] GenR;
Or event better, just use a suitable collection class that has array semantics including the []
operator. Ala vector:
std::vector<double> GenR;
GenR.resize(NumPoints);