-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpi_native.cpp
More file actions
51 lines (41 loc) · 1.17 KB
/
Copy pathpi_native.cpp
File metadata and controls
51 lines (41 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <cstdio>
#include <math.h>
#include <omp.h>
#include <random>
#define CHUNK_SIZE 1000000
#define PI 3.14159
unsigned long genSeed()
{
int threadNum = omp_get_thread_num();
return threadNum * threadNum * 77 - 22 * threadNum + 1927;
}
int main(int argc, char** argv)
{
if (argc != 2) {
printf("Specify number of workers\n");
return 1;
}
int nWorkers = std::stoi(argv[1]);
long result = 0;
int nTotal = nWorkers * CHUNK_SIZE;
printf("Estimating Pi with %i workers\n", nWorkers);
#pragma omp parallel num_threads(nWorkers) default(none) shared(nTotal) \
reduction(+ : result)
{
// Different seed per thread
std::uniform_real_distribution<double> unif(0, 1);
std::mt19937_64 generator(genSeed());
#pragma omp for
for (int i = 0; i < nTotal; i++) {
double x = unif(generator);
double y = unif(generator);
if ((x * x + y * y) <= 1.0) {
result++;
}
}
}
float pi = 4 * (((float)result) / (float)nTotal);
float error = abs(PI - pi);
printf("Pi estimate: %.5f (error %.5f)\n", pi, error);
return 0;
}