need this in c programming 422 An interesting way of calculating ? is to use a t
ID: 3700215 • Letter: N
Question
need this in c programming
422 An interesting way of calculating ? is to use a technique known as Monte Carlo, which involves randomization. This technique works as follows: Suppose you have a circle inscribed within a square, as shown in Figure hapter 4 Threads Figure 4.18 Monte Carlo technique for calculating pi. 4.18. (Assume that the radius of this circle is 1.) First, generate a series of random points as simple (x, y) coordinates. These points must fall within the Cartesian coordinates that bound the square. Of the total number of random points that are generated, some will occur within the circle. Next, estimate r by performing the following calculation: ? = 4× (number of points in circle) / (total number of points) Write a multithreaded version of this algorithm that creates a separate thread to generate a number of random points. The thread will count the number of points that occur within the circle and store that result in a global variable. When this thread has exited, the parent thread will calculate and output the estimated value of ?. It is worth experimenting with the number of random points generated. As a general rule, the greater the number of points, the closer the approximation to r. In the source-code download for this text, we provide a sample program that provides a technique for generating random numbers, as well as determining if the random (x, y) point occurs within the circle. Readers interested in the details of the Monte Carlo method for esti- mating m should consult the bibliography at the end of this chapter. In Chapter 5, we modify this exercise using relevant material from that chapterExplanation / Answer
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <math.h>
#include <stdlib.h>
int i = 0;
int amt_Wanted = 0;
int total_Pts = 0;
void count(void X)
{
for (i=0; i < amt_Wanted; i++)
{
double X = (double)rand() / RAND_MAX;
double Y = (double)rand() / RAND_MAX;
if (((X X) + (Y Y)) <= 1)
{
total_Pts++;
}
}
return NULL;
}
int main()
{
printf(" hreaded Monte Carlo ");
srand(time(NULL));
pthread_t thread;
do
{
printf(" enter a positive number for the amount of points you would like to generate? ");
scanf("%d", &amt_Wanted);
}while (amt_Wanted <= 0);
pthread_create(&thread, NULL, &count, NULL);
pthread_join(thread, NULL);
double points = 4.0 * total_Pts;
double pi = points / amt_Wanted;
printf("approximate value of pi for the desired amount of points (%d) is: %f ", amt_Wanted, pi);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.