I wrote this simple code for evaluating the π using Monte Carlo method. This is the serial version:
long double compute_pi_serial(const long interval) {
srand(time(NULL));
double x, y;
int i, circle = 0;
for (i = 0; i < interval; i ++) {
x = (double)(rand() / (double) RAND_MAX);
y = (double)(rand() / (double) RAND_MAX);
if (pow(x,2) + pow(y, 2) <= 1.0) circle ++;
}
return (long double) circle / interval * 4.0;
}
After, I wrote a parallel version using OpenMP
and this is the result:
long double compute_pi_omp(const long interval) {
double x, y;
int i, circle = 0;
#pragma omp parallel private(x, y) num_threads(omp_get_max_threads())
{
srand(SEED);
#pragma omp for reduction(+:circle)
for ( i = 0; i < interval; i++ ) {
x = (double)(rand() / (double) RAND_MAX);
y = (double)(rand() / (double) RAND_MAX);
if ( pow(x, 2) + pow(y, 2) <= 1 ) circle++;
}
}
return (long double) circle / interval * 4.0;
}
This is an efficient method or there is a most efficient version always using OpenMP
?