Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

using C code 4.22 Aninteresting way of calculating is to use a technique known a

ID: 3597004 • Letter: U

Question

using C code

4.22 Aninteresting 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 196 Chapter 4 Threads 7 1) (1 (0, 0) 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 (od random points that are generated, some will occur within the circle.) Next, estimate_by performing the following calculation: Ci -l = 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 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 estimating should consult the bibliography at the end of this chapter. In Chapter 5, we modify this exercise using relevant material from that chapter 4.23 Repeat Exercise 4.22, but instead of using a separate thread to generate random points, use OpenMP to parallelize the generation of points. Be careful not to place the calculcation of_ in the parallel region, since you want to calculcate_ only once

Explanation / Answer

#include #include #include double pi(double tolerance) { double x, y, val, error; unsigned long sampled = 0, hit = 0, i; do { /* don't check error every turn, make loop tight */ for (i = 1000000; i; i--, sampled++) { x = rand() / (RAND_MAX + 1.0); y = rand() / (RAND_MAX + 1.0); if (x * x + y * y < 1) hit ++; } val = (double) hit / sampled; error = sqrt(val * (1 - val) / sampled) * 4; val *= 4; /* some feedback, or user gets bored */ fprintf(stderr, "Pi = %f +/- %5.3e at %ldM samples. ", val, error, sampled/1000000); } while (!hit || error > tolerance); /* !hit is for completeness's sake; if no hit after 1M samples, your rand() is BROKEN */ return val; } int main() { printf("Pi is %f ", pi(3e-4)); /* set to 1e-4 for some fun */ return 0; }