forked from wncc/Hello-Foss-PyThread.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmontecarlo.cpp
52 lines (41 loc) · 1.4 KB
/
montecarlo.cpp
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
52
#include "montecarlo.h"
#include <iostream>
#include <omp.h>
#include <cstdlib>
#include <chrono>
using namespace std;
unsigned long long getCurrentTimeInMilliseconds() {
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now().time_since_epoch()).count();
}
void montecarlo(int n, int num_threads) {
int pCircle = 0, pSquare = 0;
double x, y, d;
int i;
unsigned long long seed = getCurrentTimeInMilliseconds();
srand(seed); // Seeding with a modified value
// Parallelize the loop using OpenMP
#pragma omp parallel for private(x, y, d, i) reduction(+:pCircle, pSquare) num_threads(num_threads)
for(i = 0; i < n; i++) {
// Generate random points between 0 and 1
x = (double)rand() / RAND_MAX;
y = (double)rand() / RAND_MAX;
// Calculate distance from the origin
d = x * x + y * y;
// Check if point is inside the unit circle
if(d <= 1) {
pCircle++;
}
pSquare++;
}
// Calculate and print the approximation of Pi
double pi = 4 * (double)pCircle / (double)pSquare;
cout << "Pi: " << pi << endl;
}
int main() {
int n = 1000000; // Number of points for the Monte Carlo simulation
int num_threads = 4; // Number of threads to use
// Call the Monte Carlo function to estimate Pi
montecarlo(n, num_threads);
return 0;
}