Programming Assignment ZERO: Warming Up

The purpose of this assignment is to assess whether you are familiar with Makefile and C/C++ programming. This is a calibration homework based on prerequisite material. You will receive no credit score from this assignment, but we highly encourage you to finish it. A later assignment will build upon this assignment.

Problem Statement

Suppose we toss darts randomly at a square dartboard, whose bullseye is at the origin, and whose sides are two feet in length. Suppose also that there is a circle inscribed in the square dartboard. The radius of the circle is one foot, and its area is π  square feet. If the points that are hit by the darts are uniformly distributed (and we always hit the square), then the number of darts that hit inside the circle should approximately satisfy the equation:

Number_in_Circle/Total_Number_of_Tosses = PI/4,

since the ratio of the area of the circle to the area of the square is PI/4 (π  / 4).

We can use this pseudo code to estimate the value of π  with a random number generator:

number_in_circle = 0;
for ( toss = 0; toss < number_of_tosses; toss ++) {
    x = random double between -1 and 1;
    y = random double between -1 and 1;
    distance_squared = x * x + y * y;
    if ( distance_squared <= 1)
        number_in_circle++;
}
pi_estimate = 4 * number_in_circle /(( double ) number_of_tosses);

This is called a “Monte Carlo method”, since it uses randomness (the dart tosses). Write a serial C/C++ program that uses the Monte Carlo method to estimate π , with a reasonable number of tosses. You may want to use the type of long long int for the number of hits in the circle and the number of tosses, since both may have to be very large to get a reasonable estimate of π.

Hint: You may want to check if RAND_MAX is large enough for use with rand() to get a higher precision, and if the number of tosses is great enough to reach a higher accuracy.

Requirement

You are supposed to build and run your program by simply typing make and ./pi.out. An example shows as follows.

$ make
$ ./pi.out
3.1415926....

Grading Policy

This assignment is for practice only, and you will receive no credit score from this assignment. However, some parts of the coming assignments will be based on this assignment. You should still make sure the two commands, make && ./pi.out, work as they should be.

Evaluation Platform

Your program should be able to run on UNIX-like platforms.

Submission

No submission is required for this assignment.

References