I am trying to write a c++ code which calculates an Integration b/n two numbers (a,b).
I wrote the following sequential code, but what I need to know is what is the best way to parellelize this code in order to generate the random numbers in a faster way. And is this random number generator in c++ thread safe?
The integration formula I am using is:
I = sum(f(xi))*dx and dx =(b-a)/n
double fun(double x) //f(x) = x;
{
return x;
}
double MonteCarloIntegration (double a, double b, int n)
{
if(a > b){
return MonteCarloIntegration(b, a, n);
}
double sum = 0.0;
double r= 0.0;
for (int i = 1; i <= n; i++)
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<double> dis(0.0, 1.0);
r = dis(gen);
sum = sum + fun(a+((b-a)*r));
}
sum = ((b-a)/n)*sum;
return sum;
}
int main(int argc,char * argv[]) {
if (argc < 2) {
std::cerr << "use: " << argv[0]
<< " Numer_of_Random_samples (n) \n";
std::cerr << " Example:\n " << argv[0] << " 1000000 \n\n";
return -1;
}
double b = 4.0; //lower bound
double a = 7.0; //upper bound
int n = atoi(argv[1]);
std::cout <<MonteCarloIntegration(a,b,n);
return 0;
}