---
title: "Randomness and Simulation"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 35
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/35-randomness-and-simulation
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 35 — Randomness and Simulation

Tom throws a die 60 times and gets only four sixes. He expected about ten. Is the die unfair, or is it just luck? Throwing a real die thousands of times would take days; a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) throws it a million times in a second. This chapter makes the [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) play dice, shows where its “random” numbers come from, and uses them to answer questions that are hard to work out by hand.

**You already know.**

A [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) keeps [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) in order ([Chapter 20](https://one-course.com/books/computer-science/1/en/chapter/20-lists#ch-g7-lists)); a [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) can count how often each [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) appears ([Chapter 26](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#ch-g8-dictionaries)). From mathematics: the probability of an event is a number from 0 to 1; with a fair die, each face has probability $1/6$; the frequency of an event is the number of times it happened divided by the number of tries; the area of a disc of radius $r$ is $\pi r^2$.

![Dice rolling on a table. Which face comes up depends on how they are thrown, too finely to predict: that is what makes them a game of chance.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-randomness-and-simulation/img-b4f08b9eb1e5.jpg)

*Dice rolling on a table. Which face comes up depends on how they are thrown, too finely to predict: that is what makes them a game of chance.*

## 35.1 Pseudo-random numbers and the seed

A [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer) follows its [instructions](https://one-course.com/books/computer-science/1/en/chapter/2-instructions-in-order#def-g1-instructions-in-order-instruction) exactly: given the same [instructions](https://one-course.com/books/computer-science/1/en/chapter/2-instructions-in-order#def-g1-instructions-in-order-instruction), it does the same thing. So where do random numbers come from? From a rule that mixes a number so thoroughly that the results *look* random.

**Definition 35.1 (Pseudo-random number generator).**

A *pseudo-random number generator* is a rule that keeps a hidden *state* (one number, or a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of numbers), changes it at each step and reads the next number from it, so that the sequence looks random although it is fully determined.

**Definition 35.2 (Seed).**

The *seed* of a generator is the number its state starts from. The same seed always gives the same sequence.

A tiny generator multiplies by 5, adds 3 and keeps the remainder by 16:

```python
def next_number(x):
    """A tiny generator: multiply by 5, add 3, keep the remainder by 16."""
    return (5 * x + 3) % 16


x = 7                                    # the starting number
seen = []
while x not in seen:
    seen.append(x)
    x = next_number(x)
print(seen)
print("back to", x, "after", len(seen), "numbers")
```

***Listing 35.1.** A tiny generator, run until it repeats. code/grade-9/05-randomness-and-simulation/listings/tiny_generator.py*

```
$ python tiny_generator.py
[7, 6, 1, 8, 11, 10, 5, 12, 15, 14, 9, 0, 3, 2, 13, 4]
back to 7 after 16 numbers
```

***Output 35.1.** All sixteen numbers from 0 to 15, then the same again.*

![The tiny generator’s sixteen numbers, in the order it gives them. After the sixteenth, it is back to its seed (red) and goes round again.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-randomness-and-simulation/fig-2338280c7aac.svg)

*The tiny generator’s sixteen numbers, in the order it gives them. After the sixteenth, it is back to its [seed](#def-g9-randomness-and-simulation-seed) (red) and goes round again.*

Here the state is the number itself. The numbers jump around, but they come back after 16: the generator can only produce 16 different [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), and once its state comes back, everything after it repeats. Python’s generator works on the same principle, but its state is a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of hundreds of numbers: a number it gives can come back without the sequence repeating, and the cycle of its state is far beyond anything a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) could ever use.

Python’s module `random` gives the tools. `random.seed(n)` sets the [seed](#def-g9-randomness-and-simulation-seed); `random.randint(a, b)` returns a whole number from `a` to `b`, both included; `random.random()` a decimal number from 0 up to (but not including) 1; `random.choice(items)` one [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list); `random.shuffle(items)` mixes a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) in place. Its generator, called the Mersenne Twister, repeats only after $2^{19937} - 1$ numbers. Because it is completely determined by its [seed](#def-g9-randomness-and-simulation-seed), its documentation warns that it must never be used for secrets, such as [passwords](https://one-course.com/books/computer-science/1/en/chapter/13-networks-and-the-internet-a-first-look#def-g5-networks-first-look-password); Python has another module, `secrets`, for those.

```python
import random

random.seed(2026)
print([random.randint(1, 6) for _ in range(10)])
random.seed(2026)                        # the same seed again
print([random.randint(1, 6) for _ in range(10)])
random.seed(7)                           # another seed
print([random.randint(1, 6) for _ in range(10)])
print(random.random())
```

***Listing 35.2.** The same [seed](#def-g9-randomness-and-simulation-seed), the same numbers. code/grade-9/05-randomness-and-simulation/listings/seed_demo.py*

```
$ python seed_demo.py
[1, 3, 5, 5, 6, 1, 2, 5, 5, 5]
[1, 3, 5, 5, 6, 1, 2, 5, 5, 5]
[3, 2, 4, 6, 1, 1, 5, 1, 3, 5]
0.057998924774706806
```

***Output 35.2.** The first two lines are the same.*

Every [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) of this chapter sets a [seed](#def-g9-randomness-and-simulation-seed) at the start. That is why each [output](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-input) printed in this book comes out exactly the same every time it is run, on any [computer](https://one-course.com/books/computer-science/1/en/chapter/1-what-is-a-computer#def-g1-what-is-a-computer-computer). Without `random.seed`, Python takes a [seed](#def-g9-randomness-and-simulation-seed) from the [operating system](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-os)’s sources of randomness, or from the clock, and each run gives new numbers.

## 35.2 Simulating dice, coins and draws

**Definition 35.3 (Simulation).**

A *simulation* is a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that imitates a real process, here one that involves chance, so that it can be run many times quickly.

```python
import random

random.seed(1)
throws = []
for _ in range(20):
    throws.append(random.randint(1, 6))
print("one die:  ", throws)

sums = []
for _ in range(10):
    sums.append(random.randint(1, 6) + random.randint(1, 6))
print("two dice: ", sums)

bag = ["red", "red", "red", "blue", "green"]
print("from the bag:", random.choice(bag), random.choice(bag), random.choice(bag))
```

***Listing 35.3.** A die, two dice and a bag of marbles. code/grade-9/05-randomness-and-simulation/listings/dice.py*

```
$ python dice.py
one die:   [2, 5, 1, 3, 1, 4, 4, 4, 6, 4, 2, 1, 4, 1, 4, 4, 5, 1, 6, 4]
two dice:  [9, 7, 4, 2, 7, 6, 10, 6, 7, 7]
from the bag: blue blue green
```

***Output 35.3.** Twenty throws of one die, ten of two.*

Two dice are two separate calls to `randint`, added: `randint(2, 12)` would be wrong, because it makes every sum equally likely, and with real dice a 7 is far more frequent than a 2. A deck of cards is a [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), mixed by `shuffle`:

```python
import random

random.seed(5)
deck = []
for suit in ["spades", "hearts", "diamonds", "clubs"]:
    for rank in ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]:
        deck.append(rank + " " + suit)
print(len(deck), "cards; the first three:", deck[:3])
random.shuffle(deck)
hand = deck[:5]
print("a hand of five:", hand)
print(len(deck[5:]), "cards left")
```

***Listing 35.4.** A deck, shuffled, and a hand of five. code/grade-9/05-randomness-and-simulation/listings/deck.py*

```
$ python deck.py
52 cards; the first three: ['A spades', '2 spades', '3 spades']
a hand of five: ['Q spades', '6 hearts', '10 spades', 'K diamonds', '5 clubs']
47 cards left
```

***Output 35.4.** The hand is the first five cards of the shuffled deck.*

## 35.3 Frequencies settle near the probability

Back to Tom’s question. This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) throws a die 10 times, then 20, 50, and so on up to 100,000 times, and prints the frequency of a six each time:

```python
import random

random.seed(3)
print("throws    sixes  frequency")
for throws in [10, 20, 50, 100, 200, 500, 1000, 2000, 5000,
               10_000, 20_000, 50_000, 100_000]:
    sixes = 0
    for _ in range(throws):
        if random.randint(1, 6) == 6:
            sixes = sixes + 1
    print(f"{throws:>7} {sixes:>7}  {sixes / throws:.4f}")
print(f"1/6 is {1 / 6:.4f}")
```

***Listing 35.5.** The frequency of a six, for more and more throws. code/grade-9/05-randomness-and-simulation/listings/frequencies.py*

```
$ python frequencies.py
throws    sixes  frequency
     10       1  0.1000
     20       3  0.1500
     50      10  0.2000
    100      15  0.1500
    200      26  0.1300
    500      98  0.1960
   1000     134  0.1340
   2000     332  0.1660
   5000     795  0.1590
  10000    1672  0.1672
  20000    3367  0.1683
  50000    8294  0.1659
 100000   16566  0.1657
1/6 is 0.1667
```

***Output 35.5.** From 0.1 to 0.2 at first, then close to 0.1667.*

![The frequency of a six from ; each step to the right multiplies the number of throws by 10. Far from 1/6 for a few throws, close to it for many.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-randomness-and-simulation/fig-e6e4d84ab0ac.svg)

*The frequency of a six from [Output 35.5](#out-g9-randomness-and-simulation-frequencies); each step to the right multiplies the number of throws by 10. Far from $1/6$ for a few throws, close to it for many.*

With a few dozen throws, the frequency wanders: 0.10, 0.15, 0.20. With tens of thousands, it stays within a few thousandths of $1/6$. Four sixes in 60 throws is a frequency of 0.067, lower than any point of the chart: unusual for a fair die, but with so few throws, frequencies wander a lot, and a fair die does give such a result now and then. To decide, Tom needs many more throws: with a few thousand, a fair die stays close to $1/6$, and a die that really favours some faces shows it.

## 35.4 A random walk

A token stands at 0 on a number line. At each step a coin is tossed: heads, it moves one place right; tails, one place left. Where is it after 100 steps?

```python
import random


def walk(steps):
    """The positions of a token that moves 1 left or 1 right at each step."""
    position = 0
    path = [0]
    for _ in range(steps):
        if random.random() < 0.5:
            position = position + 1
        else:
            position = position - 1
        path.append(position)
    return path


if __name__ == "__main__":
    random.seed(11)
    path = walk(100)
    print("positions at steps 0 to 10:", path[:11])
    print("end:", path[-1])
    print("farthest right:", max(path), " farthest left:", min(path))
```

***Listing 35.6.** A walk of 100 steps, left or right by a coin. code/grade-9/05-randomness-and-simulation/listings/random_walk.py*

```
$ python random_walk.py
positions at steps 0 to 10: [0, 1, 0, -1, 0, -1, -2, -1, -2, -3, -4]
end: 10
farthest right: 11  farthest left: -6
```

***Output 35.6.** One walk.*

![The walk of , step by step: it goes down to -6 early on, then drifts up and ends at 10.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-randomness-and-simulation/fig-405ac9ab29ea.svg)

*The walk of [Output 35.6](#out-g9-randomness-and-simulation-walk), step by step: it goes down to $-6$ early on, then drifts up and ends at 10.*

The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `walk` returns the whole path, so the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) can ask questions about it afterwards: the end, the farthest point on each side. Run with another [seed](#def-g9-randomness-and-simulation-seed), the walk ends somewhere else entirely. Exercise [35.12](#exo-g9-randomness-and-simulation-12) asks how often it comes back to 0.

## 35.5 Estimating by simulation

**Method 35.4 (Estimation by simulation).**

To estimate the probability of an event, simulate the random process many times, count how often the event happens, and divide by the number of tries. The more tries, the closer the frequency usually is to the probability.

What is the chance that two dice add up to 7? The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) simulates 100,000 throws, then counts exactly: of the 36 pairs of faces, 6 add up to 7.

```python
import random

random.seed(4)
throws = 100_000
sevens = 0
for _ in range(throws):
    if random.randint(1, 6) + random.randint(1, 6) == 7:
        sevens = sevens + 1
print(f"simulated: {sevens} sevens in {throws} throws, {sevens / throws:.4f}")

ways = 0
for a in range(1, 7):
    for b in range(1, 7):
        if a + b == 7:
            ways = ways + 1
print(f"exact: {ways} ways out of 36, {ways / 36:.4f}")
```

***Listing 35.7.** A seven with two dice: simulated and exact. code/grade-9/05-randomness-and-simulation/listings/sum_seven.py*

```
$ python sum_seven.py
simulated: 16758 sevens in 100000 throws, 0.1676
exact: 6 ways out of 36, 0.1667
```

***Output 35.7.** The two agree to about a thousandth.*

[Simulation](#def-g9-randomness-and-simulation-simulation) can even estimate $\pi$. Throw points at random in a square of side 1. The quarter of a disc of radius 1 covers $\pi / 4$ of the square, so about $\pi / 4$ of the points fall inside it, where $x^2 + y^2 \le 1$. Four times the fraction of points inside estimates $\pi$.

![1,000 random points in the square: blue inside the quarter disc, red outside. The blue share is close to π / 4 0.785.](https://one-course.com/images/onecourse/chapters/computer-science-1/g9-randomness-and-simulation/fig-342ab244da7b.svg)

*1,000 random points in the square: blue inside the quarter disc, red outside. The blue share is close to $\pi / 4 \approx 0.785$.*

```python
import random


def points_inside(n):
    """Throw n points in the 1 by 1 square; count those in the quarter disc."""
    inside = 0
    for _ in range(n):
        x = random.random()
        y = random.random()
        if x * x + y * y <= 1:
            inside = inside + 1
    return inside


if __name__ == "__main__":
    random.seed(8)
    for n in [100, 10_000, 1_000_000]:
        inside = points_inside(n)
        print(f"{n:>9} points: {inside:>7} inside, pi is about {4 * inside / n:.4f}")
```

***Listing 35.8.** Estimating $\pi$ with random points. code/grade-9/05-randomness-and-simulation/listings/estimate_pi.py*

```
$ python estimate_pi.py
      100 points:      82 inside, pi is about 3.2800
    10000 points:    7885 inside, pi is about 3.1540
  1000000 points:  784616 inside, pi is about 3.1385
```

***Output 35.8.** Closer to 3.14 with more points.*

A million points give $\pi$ to about two decimals only: [simulation](#def-g9-randomness-and-simulation-simulation) is a slow way to compute $\pi$, but the same method works for questions that no formula answers easily.

## 35.6 Exercises

**Exercise 35.1 ★.**

Two [programs](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) both start with `random.seed(2026)` and then print ten throws of `randint(1, 6)`. Do they print the same numbers? What if one of them sets `random.seed(2027)` instead?

**Solution of Exercise 35.1.**

Yes: the same [seed](#def-g9-randomness-and-simulation-seed) gives the same sequence, so both print the ten numbers of the first line of [Output 35.2](#out-g9-randomness-and-simulation-seed). With [seed](#def-g9-randomness-and-simulation-seed) 2027, the sequence is a different one.

**Exercise 35.2 ★.**

Another tiny generator replaces $x$ by $(3x + 1) \bmod 8$. Starting from 0, write the numbers it gives until one comes back. How long is its cycle?

**Solution of Exercise 35.2.**

$0 \to 1 \to 4 \to 5 \to 0$: $3 \times 5 + 1 = 16$, whose remainder by 8 is 0. The cycle has 4 numbers only; 2, 3, 6 and 7 never appear from this [seed](#def-g9-randomness-and-simulation-seed). A generator with a short cycle is a poor one.

**Exercise 35.3 ★.**

What can `random.choice(bag)` return for the bag of [Listing 35.3](#lst-g9-randomness-and-simulation-dice)? Which colour is the most likely, and with what probability?

**Solution of Exercise 35.3.**

`"red"`, `"blue"` or `"green"`: one [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) of the [list](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list), each [item](https://one-course.com/books/computer-science/1/en/chapter/20-lists#def-g7-lists-list) with the same chance. Red fills 3 of the 5 places, so it comes out with probability $3/5$.

**Exercise 35.4 ★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that tosses a coin 100 times with `random.choice` and prints the longest run of heads in a row.

**Solution of Exercise 35.4.**

`run` counts the heads in the current run and goes back to 0 at each tail; `longest` keeps the best run so far:

```python
import random

random.seed(9)
longest = 0
run = 0
for _ in range(100):
    if random.choice(["heads", "tails"]) == "heads":
        run = run + 1
        if run > longest:
            longest = run
    else:
        run = 0
print("longest run of heads in 100 tosses:", longest)
```

*The longest run of heads. code/grade-9/05-randomness-and-simulation/exercises/longest_heads.py*

With [seed](#def-g9-randomness-and-simulation-seed) 9, it prints 7. Runs of 6 or 7 heads in 100 tosses are common, which surprises most people.

**Exercise 35.5 ★★.**

A [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) meant to throw a die calls `random.randint(0, 6)` 70,000 times and counts each result. What does it print, roughly? What is wrong with this die?

```python
import random

random.seed(3)
counts = [0, 0, 0, 0, 0, 0, 0]
for _ in range(70_000):
    face = random.randint(0, 6)
    counts[face] = counts[face] + 1
print(counts)
```

***Listing 35.9.** Counting the faces of a die. code/grade-9/05-randomness-and-simulation/exercises/die_bug.py*

**Solution of Exercise 35.5.**

Seven counts, each close to 10,000: the run with [seed](#def-g9-randomness-and-simulation-seed) 3 prints `[10017, 9979, 10175, 9874, 9984, 9905, 10066]`. `randint(0, 6)` includes both ends, so this “die” has seven faces, 0 to 6, each with probability $1/7$ instead of $1/6$; a six comes up less often than it should.

**Exercise 35.6 ★★.**

This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) prints eight throws that are all the same. Why? Fix it.

```python
import random

throws = []
for _ in range(8):
    random.seed(2026)
    throws.append(random.randint(1, 6))
print(throws)
```

***Listing 35.10.** Eight throws. code/grade-9/05-randomness-and-simulation/exercises/seed_loop_bug.py*

**Solution of Exercise 35.6.**

`random.seed(2026)` runs at every turn of the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop), so the generator starts again from the same [seed](#def-g9-randomness-and-simulation-seed) each time and gives its first number, 1, every time. Set the [seed](#def-g9-randomness-and-simulation-seed) once, before the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop):

```python
import random

random.seed(2026)                  # once, before the loop
throws = []
for _ in range(8):
    throws.append(random.randint(1, 6))
print(throws)
```

*The [seed](#def-g9-randomness-and-simulation-seed) set once. code/grade-9/05-randomness-and-simulation/exercises/seed_loop_fixed.py*

It prints `[1, 3, 5, 5, 6, 1, 2, 5]`, the start of the first line of [Output 35.2](#out-g9-randomness-and-simulation-seed).

**Exercise 35.7 ★★.**

Two cards are drawn from a shuffled deck of 52. Estimate by [simulation](#def-g9-randomness-and-simulation-simulation) the chance that they have the same rank (two kings, two 7s…), then find it exactly.

**Solution of Exercise 35.7.**

Only the ranks matter, so the deck holds each rank four times:

```python
import random

random.seed(12)
ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
deck = []
for rank in ranks:
    for _ in range(4):                 # four suits
        deck.append(rank)
draws = 100_000
pairs = 0
for _ in range(draws):
    random.shuffle(deck)
    if deck[0] == deck[1]:
        pairs = pairs + 1
print(f"simulated: {pairs / draws:.4f}   exact: 3/51 = {3 / 51:.4f}")
```

*Two cards of the same rank. code/grade-9/05-randomness-and-simulation/exercises/pair_chance.py*

It prints `simulated: 0.0587 exact: 3/51 = 0.0588`. Exactly: whatever the first card, 3 of the 51 cards left have its rank.

**Exercise 35.8 ★★.**

A token walks on a [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid): at each step it moves one square up, down, left or right, chosen at random. Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that makes 100 steps and prints where the token ends, and how many steps it would need to walk straight back home along the [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid).

**Solution of Exercise 35.8.**

```python
import random

random.seed(6)
x = 0
y = 0
for _ in range(100):
    move = random.choice(["up", "down", "left", "right"])
    if move == "up":
        y = y + 1
    elif move == "down":
        y = y - 1
    elif move == "left":
        x = x - 1
    else:
        x = x + 1
print("end:", x, y, " steps back home along the grid:", abs(x) + abs(y))
```

*A walk on a [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid). code/grade-9/05-randomness-and-simulation/exercises/grid_walk.py*

With [seed](#def-g9-randomness-and-simulation-seed) 6, the token ends at `2 4`, 6 steps from home along the [grid](https://one-course.com/books/computer-science/1/en/chapter/33-grids-and-images#def-g9-grids-and-images-grid): 2 across and 4 up.

**Exercise 35.9 ★★.**

What is the exact probability of a double (the same face on both dice) with two dice? Count the pairs of faces.

**Solution of Exercise 35.9.**

Of the 36 pairs of faces, 6 are doubles, $(1, 1)$ to $(6, 6)$: $6/36 = 1/6$.

**Exercise 35.10 ★★★.**

A generator keeps the remainder by 16. Why can its cycle never be longer than 16 numbers, whatever the rule and the [seed](#def-g9-randomness-and-simulation-seed)?

**Solution of Exercise 35.10.**

Every number it gives is a remainder by 16, so one of the 16 [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) 0 to 15. Among any 17 numbers in a row, two must be equal. And once a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) comes back, the rule computes the same next [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) as the first time, and the next, and so on: the sequence goes round the same cycle forever. A cycle of 16 is the most it can do; the generator of the chapter reaches it.

**Exercise 35.11 ★★★.**

Using the chart of the frequency of a six, explain why a [simulation](#def-g9-randomness-and-simulation-simulation) of 100 throws can be far from $1/6$, while one of 100,000 throws rarely is. What does that mean for Tom’s 60 throws?

**Solution of Exercise 35.11.**

In [Output 35.5](#out-g9-randomness-and-simulation-frequencies), the frequencies for 10 to 500 throws range from 0.10 to 0.20; from 10,000 throws on, they stay between 0.1657 and 0.1683. With 100 throws, one six more or less moves the frequency by 0.01; with 100,000 throws, by 0.00001: a few lucky or unlucky throws cannot move it far. With 60 throws, each six moves the frequency by about 0.017, so 4 sixes instead of 10 is a big gap, but it is made of only 6 throws: Tom should throw again, many more times, before blaming the die.

**Exercise 35.12 ★★★.**

A token makes a random walk of 20 steps on a line. Estimate by [simulation](#def-g9-randomness-and-simulation-simulation) the chance that it ends where it started. Then compute the exact chance by [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program): count, step by step, the number of paths that reach each position.

**Solution of Exercise 35.12.**

The [dictionary](https://one-course.com/books/computer-science/1/en/chapter/26-dictionaries#def-g8-dictionaries-dictionary) `ways` holds, for each position, the number of paths of the steps made so far that reach it; each step sends every path one place left and one place right:

```python
import random

random.seed(20)
walks = 100_000
home = 0
for _ in range(walks):
    position = 0
    for _ in range(20):
        position = position + random.choice([-1, 1])
    if position == 0:
        home = home + 1
print(f"simulated: {home / walks:.4f}")

ways = {0: 1}                          # position: number of paths that reach it
for _ in range(20):
    new = {}
    for position in ways:
        for move in [-1, 1]:
            new[position + move] = new.get(position + move, 0) + ways[position]
    ways = new
print(f"exact: {ways[0]} paths of {2 ** 20}, {ways[0] / 2 ** 20:.4f}")
```

*Back home after 20 steps. code/grade-9/05-randomness-and-simulation/exercises/walk_return.py*

It prints `simulated: 0.1768`, then `exact: 184756 paths of 1048576, 0.1762`: of the $2^{20}$ equally likely walks, 184,756 end at 0. The [simulation](#def-g9-randomness-and-simulation-simulation) is right to about a thousandth.

## 35.7 Problem: The Birthday Surprise

**Problem 35.1.**

Weekend problem — the birthday surprise

In a class of 23 pupils, how likely is it that two of them share a birthday? Most people guess that it is rare. In this problem a year has 365 days, each equally likely to be a birthday.

**Part I — By hand.**

1. Why do 366 pupils always include two with the same birthday?
2. In a class of 2, what is the chance that the two share a birthday?
3. Guess the chance for 23 pupils before going on.

**Part II — Simulation.**

```python
import random


def shared(size):
    """Simulate one class: True if two pupils share a birthday."""
    seen = []
    for _ in range(size):
        day = random.randint(1, 365)
        if day in seen:
            return True
        seen.append(day)
    return False


def frequency(size, classes):
    count = 0
    for _ in range(classes):
        if shared(size):
            count = count + 1
    return count / classes


if __name__ == "__main__":
    random.seed(23)
    for size in [5, 10, 15, 20, 23, 25, 30, 40, 50, 60]:
        print(f"{size:>2} pupils: {frequency(size, 10_000):.3f}")
```

***Listing 35.11.** Simulating 10,000 classes of each size. code/grade-9/05-randomness-and-simulation/listings/birthday.py*

4. What does `shared` return, and why can it stop before the end of the class?
5. Run the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) . What frequency does it find for 23 pupils?
6. From which size is a shared birthday more likely than not?
7. Why is the frequency for 60 pupils so close to 1?

**Part III — The exact chance.**

```python
def exact(size):
    """The chance that two of size pupils share a birthday (365 days)."""
    all_different = 1
    for k in range(size):
        all_different = all_different * (365 - k) / 365
    return 1 - all_different


for size in [5, 10, 15, 20, 23, 25, 30, 40, 50, 60]:
    print(f"{size:>2} pupils: {exact(size):.3f}")
size = 1
while exact(size) <= 0.5:
    size = size + 1
print("smallest class above one half:", size, f"({exact(size):.4f})")
```

***Listing 35.12.** The exact chance, as a product of fractions. code/grade-9/05-randomness-and-simulation/listings/birthday_exact.py*

8. Explain the product: why does pupil number $k + 1$ multiply the chance that all birthdays differ by $(365 - k) / 365$ ?
9. Run it. What is the exact chance for 23 pupils?
10. Compare the [simulation](#def-g9-randomness-and-simulation-simulation) with the exact [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) . How close are they?
11. Why is the answer so much larger than most guesses? Count the pairs of pupils in a class of 23.
12. State the result.

**Solution of Problem 35.1.**

**1.** There are only 365 possible birthdays: once 365 pupils all have different ones, the 366th must share one of them.

**2.** Whatever the first birthday, the second matches it with probability $1/365$, about 0.003.

**3.** Any guess will do: most people say about 0.05 or 0.1.

**4.** `True` as soon as a birthday appears twice; once that has happened, the rest of the class cannot change the answer.

```
$ python birthday.py
 5 pupils: 0.024
10 pupils: 0.119
15 pupils: 0.249
20 pupils: 0.416
23 pupils: 0.517
25 pupils: 0.570
30 pupils: 0.704
40 pupils: 0.888
50 pupils: 0.973
60 pupils: 0.995
```

***Output 35.9.** 10,000 simulated classes of each size.*

**5.** 0.517.

**6.** From 23 pupils: 20 give 0.416, 23 give 0.517.

**7.** With 60 pupils there are so many pairs that a class without a shared birthday is very rare: 0.995 means about 5 classes in 1,000.

**8.** For all birthdays to differ, pupil $k + 1$ must avoid the $k$ days already taken: $365 - k$ of the 365 days. Multiplying these fractions gives the chance that all differ; one minus it is the chance of a shared birthday.

```
$ python birthday_exact.py
 5 pupils: 0.027
10 pupils: 0.117
15 pupils: 0.253
20 pupils: 0.411
23 pupils: 0.507
25 pupils: 0.569
30 pupils: 0.706
40 pupils: 0.891
50 pupils: 0.970
60 pupils: 0.994
smallest class above one half: 23 (0.5073)
```

***Output 35.10.** The exact chances.*

**9.** 0.5073, and 23 is the smallest class above one half.

**10.** Within 0.01 for every size: 0.517 against 0.507 for 23, 0.416 against 0.411 for 20. 10,000 classes give about two decimals.

**11.** A shared birthday can be between any two pupils, not only with you: a class of 23 has $23 \times 22 / 2 = 253$ pairs, each a chance of a match.

**12.** **Result.** With 23 pupils, the chance of a shared birthday is already about 0.507, more likely than not. The [simulation](#def-g9-randomness-and-simulation-simulation) of 10,000 classes and the exact product agree within 0.01 for every size from 5 to 60.
