To determine if a point falls within the circle we know that the diameter of a c
ID: 3728815 • Letter: T
Question
To determine if a point falls within the circle we know that the diameter of a circle can be computed by d = sqrt(x2 + y2). Therefore, if the sqrt(x2 + y2) <= 1.0 then the point falls on or within the circle. Your program should implement the Monte Carlo method by generating at least 5 million points (preferably 10 million points), e.g., n=10,000,000 random points and compute the ratio of the points on or within the circle over the total number of points used. Note each point is represented by (x, y) so each iteration will require 2 random values between -1.0 and 1.0 inclusive, one for x and one for y. You should run your program varying the number of threads (t) from t=1 to 10. Each thread should compute n/t iterations of the experiment and return the number of points on or within the circle to the master. The master can then aggregate the results over all the threads to compute the final estimated value of PI. Please turn in your program along with the plots for execution time vs. number of threads by midnight of the due date.
Explanation / Answer
Please find the below code for finding out the value of PI using Monte Carlo method.
The macro NUMTHREADS could be changed from 1 to 10
The macro TOTCOUNT could be changed to 5000000 or 10000000 according to the question given.
The code prints the number of points in circle and prints the value of PI in the end.
You could compute the time of the program by using time command and modifying the number of threads.
Program below
#include <stdio.h>
#include <pthread.h>
#include <math.h>
#include <stdlib.h>
#define NUMTHREADS 100 // this is t in the given question.
#define TOTCOUNT 1000000 // this is n in the given question.
/*
* Generates Random number between 1 and -1
*/
double randNumGenerator() {
return -1.0+2.0*((double)rand())/RAND_MAX;
}
void* calc(void *tid) {
//int threadId = *((int*)tid);
// the variable must not destroy if thread is killed;
int *inCnt = (int *) malloc(sizeof (int));
int tot_iter = TOTCOUNT / NUMTHREADS;
int i;
for(i = 0; i< tot_iter; i++) {
double x = randNumGenerator();
double y = randNumGenerator();
double dist = sqrt(x * x + y * y);
if(dist <= 1) {
(*inCnt)++;
}
}
pthread_exit((void *)inCnt);
}
int main() {
int i;
int err;
pthread_t threads[NUMTHREADS];
void* inCount;
int totInCount = 0;
for(i = 0; i < NUMTHREADS; i++) {
err = pthread_create(&threads[i], NULL, calc, (void*)&i);
if(err){
printf("ERROR creating THREADS, return code %d ",err);
exit(-1);
}
}
for(i = 0; i < NUMTHREADS; i++) {
pthread_join(threads[i], &inCount);
totInCount += *(int*)inCount;
printf("points in circle%d ",totInCount);
}
double pi = (double)totInCount / (double)TOTCOUNT;
printf("%lf ",pi * 4.0);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.