CS 1005, C Term 2000
Techniques of Programming
Lab 5 (Feb. 16)


In this lab you will use a random number generator to produce random points in an n-dimensional cube. In other words, you will implement the RandPoint function needed in HW3. You will also test this function within a Monte Carlo simulation to estimate the area of a two-dimensional region bounded by curves (if you know calculus, you will recognize the area as the integral between x=0 and x=1 of the function f(x)=x2). A sample run of the finished program is available here. For a very brief introduction to Monte Carlo simulation, see the statement of HW 3.

  1. Sign in with the TA. You should both print your name and sign the sheet.
  2. Listen to the TA's mini-lecture.
  3. Do the problems listed below. Feel free to ask the TA questions about the problems. Don't worry if you can't finish all of the problems before the lab session is over. You can finish afterwards. However, actively working on the lab assignment during the lab session is required.


  1. Log onto your CCC Unix account. Change the working directory to your CS1005 directory. Create a subdirectory named Lab5 and change the working directory to Lab5. Copy the files named lab5.cxx, randgen.h, and randgen.cpp from the /cs/cs1005/samples/lab5/ directory to your Lab5 directory.

  2. Study the file named lab5.cxx. This file contains a skeleton for the Lab5 assignment. Notice the typedef near the top of the file. This typedef declares the identifier point to be a synonym for the type vector<double>. The main() function prompts the user to enter an integer n and proceeds to carry out n Monte Carlo steps. Each step consists of generating a random 2D point and incrementing a hits counter if the point lies within the target region, which for Lab5 is the set of all points (x,y) such that 0 < x < 1 and 0 < y < x2. The program then reports the Monte Carlo estimate of the area of the target region.

  3. Fill in the missing statements in main() in a way that's consistent with the above description of the behavior of the program. Then implement the function named RandPoint. Use the RandReal member function for the latter purpose. You will need to define an object of type RandGen and an object of type point of the appropriate size; invoke RandReal on the RandGen object once for each coordinate of the point to be generated and place the resulting random number in the appropriate position of the point object; when all positions have been filled, return the resulting point object.

  4. Compile your program using the following command line:
       g++ -o lab5prog lab5.cxx randgen.cpp
    Debug your program as needed. Try out your program for different numbers of Monte Carlo iterations.

  5. Use any remaining time to continue working on HW3.