Random Number Generators

Exercise 1

Run each of the following examples within Scheme several times

Sample Procedure Call Type of Value Returned
(random 10) random integer 0, 1, ..., 9
(random 6) random integer 0, 1, ..., 5
(random 1.0) random nonnegative real number less than 1.0

For example, you might enter (random 6) into the computer ten times.

Describe what results.

Exercise 2

Type (random 1). Why do you think the result always is 0?

Exercise 3

What happens if you type (random -5)?

Exercise 4

The following procedure simulates the roll of a die:


   (define roll-a-die 
      (lambda ()             ;;; (random 6) gives integers 0,1,2,3,4,5
          (+ 1 (random 6))   ;;; so add 1 to get integers  1,2,3,4,5,6
      )
   )

Enter the definition of roll-a-die into Scheme. Confirm that roll-a-die works correctly by typing (roll-a-die) several times.

Exercise 5

Explain why the parentheses are needed when running the roll-a-die procedure.
(Consider, for example, what happens if roll-a-die is typed without the parentheses.)

Exercise 6

To roll a die n times, we could construct a list with each result of calling the roll-a-die procedure. A parameter n allows us to count the number of rolls left to go.


   (define roll
      (lambda (n)
         (if (<= n 0)
             '()          ;;; rolling a die 0 times gives null list
             (cons (roll-a-die) (roll (- n 1))))  
                          ;;; add current roll to list of rest
      )
   )

Enter the definition of roll into Scheme, and check that it works correctly.
Explain in a few sentences why roll simulates the rolling of a die.

What happens if you call (roll 10) several times?
Do you get the same list of 10 die rolls each time?

Exercise 7

Modify your previous work to obtain a procedure count-2s, which counts the number of 2's rolled when a die is thrown n times.

Exercise 8

We can simulate the tossing of a coin by generating real numbers between 0 and 1 and then considering a "head" to correspond to a number less than 0.5.

Write a procedure coin which simulates the flipping of a coin.
(coin should return either the string "head" or the string "tail".)


This document is available on the World Wide Web as

http://www.math.grin.edu/~walker/courses/151.sp04/labs/random-numbers.xhtml

created February 5, 1997
last revised January 16, 2004
Validated as XHTML 1.0 by the World Wide Web Consortium Cascading Style Sheet validated by the World Wide Web Consortium
For more information, please contact Henry M. Walker at walker@cs.grinnell.edu.