4.5. Pseudorandomness#
You will have noticed that every time you generate random numbers, the values change! However, recreating the same set of random numbers is often important to ensure your results are reproducible. Lucky for us, the random numbers generated by the computer aren’t truly random. They’re what we call pseudorandom. If you kept generating random numbers for long enough, the sequence would repeat!
To force our random numbers to start at the same point in the sequence every time, we can use a seed. We use
random.seed(seed)
where seed is an integer. Here’s an example. You’ll see that the program will always generate the same results.
import random
random.seed(0)
print(random.random())
print(random.random())
print(random.random())
If you don’t use a seed you will get different results every time.
You may have seen seeds mentioned in computer games when you want to reproduce the same conditions e.g. generating the same starting map.
Question 1
You run the following program
import random
random.seed(0)
print(random.randrange(6))
The program outputs
3
What happens when you run the program again?
You are guaranteed to get the number 3 again.
It’s impossible to say as you’ll get either a 0, 1, 2, 3, 4 or 5.
Solution
A.
Since a seed is set we will get the same value each time we run this program
Question 2
You run the following program
import random
random.seed(0)
print(random.randrange(6))
print(random.randrange(6))
print(random.randrange(6))
Which of the following could be possible outputs from this program given your knowledge from question 1? Select all that apply.
3 1 4
3 3 3
4 5 6
3 9 4
3 0 0
Solution
Solution is locked
Question 3
You run the following program
import random
random.seed(0)
print(random.randrange(6))
print(random.randrange(6))
print(random.randrange(6))
random.seed(0)
print(random.randrange(6))
print(random.randrange(6))
print(random.randrange(6))
Which of the following could be possible outputs from this program given your knowledge from question 1? Select all that apply.
3 3 0 3 5 4
5 5 1 5 5 1
3 3 0 3 3 0
3 3 0 4 1 3
Solution
Solution is locked