5.5. Random numbers

If you give most computer programs the same input multiple times, they will always produce exactly the same output. Programs like this are said to be deterministic. Determinism is usually a good thing, since we expect the same calculation to yield the same result. For some applications, though, we want the computer to be unpredictable. Games are an obvious example, but there are more.

Making a program truly nondeterministic turns out to be no easy task, but there are ways to make programs at least seem nondeterministic. One way is to use algorithms that generate pseudorandom numbers. Pseudorandom numbers are not truly random because they are generated by a deterministic computation, but just by looking at the numbers it is all but impossible to distinguish them from a truly random set.

The random module provides functions that generate pseudorandom numbers (which I will simply call “random” from here on).

The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you call random, you get the next number in a long series. To see a sample, run this loop:

This program produces the following list of 10 random numbers between 0.0 and up to but not including 1.0. Notice how the numbers you ran above are different than the ones below, which were generated earlier.

0.11132867921152356
0.5950949227890241
0.04820265884996877
0.841003109276478
0.997914947094958
0.04842330803368111
0.7416295948208405
0.510535245390327
0.27447040171978143
0.028511805472785867

Run the program more than once and see what numbers you get.

The random function is only one of many functions that handle random numbers. The function randint takes the parameters low and high, and returns an integer between low and high (including both).

To choose an element from a sequence at random, you can use choice:

The random module also provides functions to generate random values from continuous distributions including Gaussian, exponential, gamma, and a few more.

Construct a block of code that correctly generates a random integer between 1 and 100 (inclusive), then prints it out. Hint: there are two code blocks that are not used.

Construct a block of code that correctly generates a random number from the list called “nums”, then prints it out. Hint: there are four code blocks that are not used.

You have attempted of activities on this page