CPSC 427a: Object-Oriented Programming

Michael J. Fischer

Lecture 7
September 23, 2010

subsection in toc subsection in toc subsection in toc

Remarks on Problem Sets

Problem Set 1

Seth Hamman

Problem Set 2

Random number generation and simulations

Pseudorandom number generators You will need to generate random numbers in this assignment.

A few remarks on random number generation are in order.

Random numbers in C++

rand() and srand()

Basic properties

Generating uniform distribution over a discrete interval

To generate a uniformly distributed number u ∈{0,1,,n - 1}:

Generating random doubles

To generate a double in the semi-open interval [01):

(double) rand() / ( (double)(RAND_MAX) + 1.0 )

Alternate method for generating uniform distribution over a discrete interval

To generate a uniformly distributed number u ∈{0,1,,n - 1}:

  1. #include <cmath>.
  2. Generate a uniformly distributed random double u in [01).
  3. Compute trunc(n*u).

Question: Is this truly uniform over {0,1,,n - 1}?

Generating exponential distribution

[Not needed for PS2 but useful to know.]

To generate a double according to the exponential distribution with parameter lambda:

  1. #include <cmath>.
  2. Generate a uniformly distributed random double u in [01).
  3. Compute -log(1.0-u)/lambda.

Note: log(0.0) is undefined. Will return a special value that prints as -inf.

Bar Graph Demo

We look at the Bar Graph demo from Chapter 8 of the textbook.

class Graph {  
  private:  
    Row* bar[BARS]; // List of bars (aggregation)  
    void insert( char* name, int score );  
  public:  
    Graph ( istream& infile );  
    ~Graph();  
    ostream& print ( ostream& out );  
    // Static functions are called without a class instance  
    static void instructions() {  
      cout  << "Put input files in same directory "  
               "as the executable code.\n";  
    }  
};  
inline ostream& operator<<( ostream& out, Graph& G) {  
    return G.print( out );  
}