Simulation Using Random Numbers

We can simulate the rolling a pair of dice by calling roll-a-die twice -- perhaps making a list out of the two results:


   (define pair-of-dice
       (lambda ()
           (list (roll-a-die) (roll-a-die))
       )
   )

Exercise 1

Check that pair-of-dice works correctly.

Exercise 2

Combine the ideas of procedures roll and pair-of-dice to obtain a procedure roll-dice that shows the results of throwing a pair of dice n times.

Exercise 3

Modify pair-of-dice to obtain a new procedure sum-of-dice that returns the sum of two dice. (As with pair-of-dice, the sum-of-dice procedure should not require any parameters.)

Exercise 4

Modify roll to obtain a procedure count-7s, which counts the number of 7's rolled when a pair of dice is thrown n times.

Tossing Coins

Previous laboratory work also showed how to 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.

Exercise 5

Build on your previous work by writing a procedure tosses which simulates the flipping of a coin n times. The results of each toss should be placed on a list.

Exercise 6

Write a procedure number-of-heads that counts the number of heads that are obtained in n tosses.

Challenge Problem 1:

Consider the problem of rolling a pair of dice n times and counting the number of times that either a 7 or an 11 comes up.

What is wrong with the following procedure to accomplish this task?


   (define seven-or-11
       (lambda (n)
           (cond  ((<= n 0)  0)
                  ((or (= (sum-of-dice) 7) (= (sum-of-dice) 11))
                        (+ 1 (seven-or-11 (- n 1))))
                  (else (seven-or-11 (- n 1)))
           )
       )
   )

Write a correct procedure to solve this problem.

Challenge Problem 2:

Write a procedure double-heads which tosses a coin n times and determines whether a head ever comes up twice in a row.
(Hint: You might try adding another parameter which indicates if the previous toss were a head.)

Challenge Problem 3:

Modify the previous procedure to record the number of times a double head is obtained when a coin is tossed n times. (In your counting, you should consider three heads in a row as two double heads.)

Challenge Problem 4:

Modify your procedure from Challenge Problem 2, so that it continues the simulation until a double head appears and then prints the number of flips that were required to get the double head.


This document is available on the World Wide Web as

http://www.math.grin.edu/~walker/courses/151.sp04/readings/simple-simulations.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.