In: Computer Science
Develop a program using Threads in C/C++ to estimate the value of PI using the Monte Carlo method
use:
C/C++ #include srand((unsigned)(myid)); x = ((double)rand()) / ((double)RAND_MAX); y = ((double)rand()) / ((double)RAND_MAX);
Your program will allow the user to specify the number of threads (range 1 to 10) and the total number of data points (range 10 to 1,000,000) used for the Monte Carlo simulation on the command line. Note, DO NOT assume the number of data points is always evenly divisible by the number of threads.
Hello. I am giving the answer of the above question in C++. If you have any doubt in this just ask me in the comments section.
#include <bits/stdc++.h>
#define INTERVAL 10000
using namespace std;
void main()
{
int interval; int i;
double rand_x, rand_y, originDist, pi;
int circle_points = 0, square_points = 0;
srand(time(NULL));
for (i = 0; i < (INTERVAL * INTERVAL); i++) {
rand_x = double(rand() % (INTERVAL
+ 1)) / INTERVAL;
rand_y = double(rand() % (INTERVAL
+ 1)) / INTERVAL;
originDist = rand_x * rand_x +
rand_y * rand_y;
if (originDist <= 1)
circle_points++;
square_points++;
pi = double(4 * circle_points) /
square_points;
cout << rand_x << " " << rand_y << " " << circle_points << " " << square_points << " - " << pi << endl << endl;
if (i < 20)
getchar();
}
cout << "\n Final Estimation of Pi = " <<
pi;
}