0

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;
}
DMH16
  • 123
  • 5
  • You have a limited amount of stack memory to use. `double GenR[NumPoints]` is probably consuming all the memory that you have. To solve this, try to alloc it using the heap memory – Amadeus Sep 10 '19 at 01:33
  • "_I encounter a problem_" Which is...? "_the program does not work_" Doesn't work... How? – Algirdas Preidžius Sep 10 '19 at 01:33
  • @AlgirdasPreidžius it runs the code, but does not show any output and states that the return value is 3221225725 – DMH16 Sep 10 '19 at 01:35
  • @Amadeus I am sorry, but how would I go about doing that? I am a beginner in c++ and I do not actually know what heap memory means – DMH16 Sep 10 '19 at 01:37
  • @DMH16 So, why such information isn't in the question? It tells exactly what's wrong: 3221225725 = 0xC00000FD = "Stack overflow". The most likely culprit for it, is your array. Just use `std::vector`. If you are a beginner, consider learning C++, in a structured way, from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead. – Algirdas Preidžius Sep 10 '19 at 01:38
  • @SamVarshavchik Note that the linked duplicate talks about C, not C++. While the answer is still very similar, there are some differences between a C and C++ solution. –  Sep 10 '19 at 03:18

1 Answers1

3

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);
selbie
  • 100,020
  • 15
  • 103
  • 173