এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
Primary & Middle School Computer Science · শ্রেণি 1–9
35Randomness 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 throws it a million times in a second. This chapter makes the 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 keeps values in order (Chapter 20); a dictionary can count how often each value appears (Chapter 26). From mathematics: the probability of an event is a number from 0 to 1; with a fair die, each face has probability ; 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 is .
35.1 Pseudo-random numbers and the seed
A computer follows its instructions exactly: given the same instructions, 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 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:
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")
$ 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
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, and once its state comes back, everything after it repeats. Python’s generator works on the same principle, but its state is a 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 could ever use.
Python’s module random gives the tools. random.seed(n) sets the 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 of a list; random.shuffle(items) mixes a list in place. Its generator, called the Mersenne Twister, repeats only after numbers. Because it is completely determined by its seed, its documentation warns that it must never be used for secrets, such as passwords; Python has another module, secrets, for those.
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())
$ 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
Every program of this chapter sets a seed at the start. That is why each output printed in this book comes out exactly the same every time it is run, on any computer. Without random.seed, Python takes a seed from the operating system’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 that imitates a real process, here one that involves chance, so that it can be run many times quickly.
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))
$ 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
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, mixed by shuffle:
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")
$ 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
35.3 Frequencies settle near the probability
Back to Tom’s question. This 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:
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}")
$ 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
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 . 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 , 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?
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))
$ 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
The function walk returns the whole path, so the program can ask questions about it afterwards: the end, the farthest point on each side. Run with another seed, the walk ends somewhere else entirely. Exercise 35.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 simulates 100,000 throws, then counts exactly: of the 36 pairs of faces, 6 add up to 7.
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}")
$ python sum_seven.py
simulated: 16758 sevens in 100000 throws, 0.1676
exact: 6 ways out of 36, 0.1667
Simulation can even estimate . Throw points at random in a square of side 1. The quarter of a disc of radius 1 covers of the square, so about of the points fall inside it, where . Four times the fraction of points inside estimates .
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}")
$ 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
A million points give to about two decimals only: simulation is a slow way to compute , but the same method works for questions that no formula answers easily.
35.6 Exercises
Exercise 35.1 ★
Two programs 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
Solution of Exercise 35.1.
Yes: the same seed gives the same sequence, so both print the ten numbers of the first line of Output 35.2. With seed 2027, the sequence is a different one.
Exercise 35.2 ★
Another tiny generator replaces by . Starting from 0, write the numbers it gives until one comes back. How long is its cycle?
Solution
Solution of Exercise 35.2.
: , whose remainder by 8 is 0. The cycle has 4 numbers only; 2, 3, 6 and 7 never appear from this 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? Which colour is the most likely, and with what probability?
Exercise 35.4 ★
Write a program that tosses a coin 100 times with random.choice and prints the longest run of heads in a row.
Solution
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:
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)
With 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 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?
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)
Solution
Solution of Exercise 35.5.
Seven counts, each close to 10,000: the run with 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 instead of ; a six comes up less often than it should.
Exercise 35.6 ★★
This program prints eight throws that are all the same. Why? Fix it.
import random
throws = []
for _ in range(8):
random.seed(2026)
throws.append(random.randint(1, 6))
print(throws)
Solution
Solution of Exercise 35.6.
random.seed(2026) runs at every turn of the loop, so the generator starts again from the same seed each time and gives its first number, 1, every time. Set the seed once, before the loop:
import random
random.seed(2026) # once, before the loop
throws = []
for _ in range(8):
throws.append(random.randint(1, 6))
print(throws)
It prints [1, 3, 5, 5, 6, 1, 2, 5], the start of the first line of Output 35.2.
Exercise 35.7 ★★
Two cards are drawn from a shuffled deck of 52. Estimate by simulation the chance that they have the same rank (two kings, two 7s…), then find it exactly.
Solution
Solution of Exercise 35.7.
Only the ranks matter, so the deck holds each rank four times:
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}")
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: at each step it moves one square up, down, left or right, chosen at random. Write a 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.
Solution
Solution of Exercise 35.8.
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))
With seed 6, the token ends at 2 4, 6 steps from home along the 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
Solution of Exercise 35.9.
Of the 36 pairs of faces, 6 are doubles, to : .
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?
Solution
Solution of Exercise 35.10.
Every number it gives is a remainder by 16, so one of the 16 values 0 to 15. Among any 17 numbers in a row, two must be equal. And once a value comes back, the rule computes the same next 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 of 100 throws can be far from , while one of 100,000 throws rarely is. What does that mean for Tom’s 60 throws?
Solution
Solution of Exercise 35.11.
In Output 35.5, 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 the chance that it ends where it started. Then compute the exact chance by program: count, step by step, the number of paths that reach each position.
Solution
Solution of Exercise 35.12.
The 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:
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}")
It prints simulated: 0.1768, then exact: 184756 paths of 1048576, 0.1762: of the equally likely walks, 184,756 end at 0. The 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.
- Why do 366 pupils always include two with the same birthday?
- In a class of 2, what is the chance that the two share a birthday?
- Guess the chance for 23 pupils before going on.
Part II — Simulation.
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}")
- What does
sharedreturn, and why can it stop before the end of the class? - Run the program. What frequency does it find for 23 pupils?
- From which size is a shared birthday more likely than not?
- Why is the frequency for 60 pupils so close to 1?
Part III — The exact chance.
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})")
- Explain the product: why does pupil number multiply the chance that all birthdays differ by ?
- Run it. What is the exact chance for 23 pupils?
- Compare the simulation with the exact values. How close are they?
- Why is the answer so much larger than most guesses? Count the pairs of pupils in a class of 23.
- State the result.
Solution
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 , 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
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 must avoid the days already taken: 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)
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 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 of 10,000 classes and the exact product agree within 0.01 for every size from 5 to 60.