COMP 102 · Lecture 23 · Randomness and Simulation

Dice Lab

A Die

Python's random.randint(1, 6) gives 1, 2, 3, 4, 5 or 6. Both ends are in.

0rolls so far
>>> import random

Each face should come up about 1 time in 6 (the dashed line). Few rolls: bumpy. Many rolls: flat.

Two Dice: Total of 7?

By hand: 6 of the 36 pairs make 7, so the chance is 6/36 = 0.1667. Does the recipe find it? Throw many times, count the sevens, divide.

tries0
sevens0
sevens ÷ tries–
exact0.1667
def chance_of_seven(n):
    hits = 0
    for i in range(n):
        a = random.randint(1, 6)
        b = random.randint(1, 6)
        if a + b == 7:
            hits += 1
    return hits / n

Bars: what you threw. Red dashes: the exact answer. 100 times more tries gives about 1 more correct digit.

Roll or Stop

On your turn: roll and add. Stop when you like and keep the points. A 1 wipes out this turn's points.

1turn
0this turn
0kept (goal 100)
Press ROLL to start.

The turns

No turns yet.

Try this

  1. Play one game your own way. How many turns to reach 100?
  2. Play again, but always stop at 10 or more.
  3. Play again, but always stop at 20 or more.
  4. Which plan was best? One game is luck. Tab 4 plays thousands.

The Best h

Plan: keep rolling until this turn has at least h points. Which h gets the most points per turn?

20

      

100,000 turns for each bar.

Who Wins the Game?

Two players race to 100. Each one stops at their own h. They take turns going first. Most points per turn is not always most wins!

Your numbers will change a little each time you press. That is randomness. More games: steadier numbers.