Simulation Using Random Numbers

## Simulation Using Random Numbers

Goals: This laboratory applies random number generators to a range of experiments involving the multiple rolls of dice and multiple tosses of a coin.

Previous laboratory work simulated the rolling of a die, by defining a procedure roll-a-die using Chez Scheme's random procedure to obtain random integers 1, 2, 3, 4, 5, and 6. That work also simulated the rollng of a die several times, showing the results of each of n tosses. The resulting procedure was called roll.

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))
)
)
```
1. Check that pair-of-dice works correctly.

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.

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.)

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.
1. 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.

2. 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/lab-simulation.html
```

created February 5, 1997
last revised February 7, 1997