Skip to main content

Section 3.10 The random module

Subsection 3.10.1 Motivation for Randomness

We often want to use random numbers in programs. Here are a few typical uses:
  • To play a game of chance where the computer needs to throw some dice, pick a number, or flip a coin,
  • To shuffle a deck of playing cards randomly,
  • To randomly allow a new enemy spaceship to appear and shoot at you,
  • To simulate possible rainfall when we make a computerized model for estimating the environmental impact of building a dam,
  • For encrypting your banking session on the Internet.
Python provides a module random that helps with tasks like this. You can take a look at it in the documentation. Here are the key things we can do with it.
Press the run button a number of times. Note that the values change each time. These are random numbers.
The randrange function generates an integer between its lower and upper argument where the lower bound is included, but the upper bound is excluded. So, randrange(1,7) will include numbers from 1-6. If you omit the first parameter it is assumed to be 0 so randrange(10) will give you numbers from 0-9. All the values have an equal probability of occurring (i.e. the results are uniformly distributed).
The random() function returns a floating point number in the range [0.0, 1.0) — the square bracket means “closed interval on the left” and the round parenthesis means “open interval on the right”. In other words, 0.0 is possible, but all returned numbers will be strictly less than 1.0. It is usual to scale the results after calling this method, to get them into a range suitable for your application.
In the case shown below, we’ve converted the result of the random() method call to a number in the range [0.0, 5.0). Once more, these are uniformly distributed numbers — numbers close to 0 are just as likely to occur as numbers close to 3, or numbers close to 5. If you continue to press the run button you will see random values between 0.0 and up to but not including 5.0.
It is important to note that random number generators are based on a deterministic algorithm — repeatable and predictable. So they’re called pseudo-random generators — they are not genuinely random. They start with a seed value. Each time you ask for another random number, you’ll get one based on the current seed attribute, and the state of the seed (which is one of the attributes of the generator) will be updated. The good news is that each time you run your program, the seed value is likely to be different meaning that even though the random numbers are being created algorithmically, you will likely get random behavior each time you execute.

Note 3.10.1.

Another useful function is random.choice() which requires a sequence type variable as a parameter. Run the activecode below to randomly choose a colour from the list and a character from a string. You will see this function again in class assignments!

Subsection 3.10.2 Randomness and Ethics

Using random numbers in your programming can be a good way to help ensure fairness. If you have a list of students and you want to choose students to give presentations in a class, using a program that randomly picks a student is likely better than starting alphabetically. If all instructors did this alphabetically, the students whose surnames start with an ‘A’ or ‘B’ would always get the chance to present and get feedback and students whose surnames begin with a letter later in the alphabet would not receive the same opportunity. Can you think of software programs that you use that have random elements? How would the program be less fair if it didn’t use randomness?
Check your understanding

Checkpoint 3.10.2.

    The correct code to generate a random number between 1 and 100 (inclusive) is:
  • prob = random.randrange(1, 101)
  • This will generate a number between 1 and 101, but does not include 101.
  • prob = random.randrange(1, 100)
  • This will generate a number between 1 and 100, but does not include 100. The highest value generated will be 99.
  • prob = random.randrange(0, 101)
  • This will generate a number between 0 and 100. The lowest value generated is 0. The highest value generated will be 100.
  • prob = random.randrange(0, 100)
  • This will generate a number between 0 and 100, but does not include 100. The lowest value generated is 0 and the highest value generated will be 99.

Checkpoint 3.10.3.

    One reason that lotteries don’t use computers to generate random numbers is:
  • There is no computer on the stage for the drawing.
  • They could easily put one there.
  • Because computers don’t really generate random numbers, they generate pseudo-random numbers.
  • Computers generate random numbers using a deterministic algorithm. This means that if anyone ever found out the algorithm they could accurately predict the next value to be generated and would always win the lottery.
  • They would just generate the same numbers over and over again.
  • This might happen if the same seed value was used over and over again, but they could make sure this was not the case.
  • The computer can’t tell what values were already selected, so it might generate all 5’s instead of 5 unique numbers.
  • While a programmer would need to ensure the computer did not select the same number more than once, it is easy to ensure this.

Checkpoint 3.10.4.

    We are writing code to shuffle a deck of cards. How do we guarantee 100% fairness when using random numbers in our code?
  • Run it 10 times and make sure the deck is shuffled differently every time
  • Does fairness in random mean ’different each time’? How does this help us for the 11th run or 12th?
  • Run it 1000 times and make sure the deck is shuffled differently every time
  • Does fairness in random mean ’different each time’? How does this help us for the 1001th run or 2000th?
  • Run it 1000 times and make sure the deck is shuffled differently 90% of the time. 90% is close enough.
  • Sometimes a 90% confidence might be ok but 90% does not guarantee fairness ALL the time.
  • It’s not possible to guarantee 100% of the time.
  • Correct. We can’t 100% of the time guarantee the fairness using pseudo-random generation. What we can do is be aware of our code’s limitations, run some statistics on likelihood of fairness (like answer c would suggest) and continuously look for ways to pursue fairness in random numbers and algorithms.
You have attempted of activities on this page.