You are here

Random numbers

23 February, 2015 - 14:13

Given the same inputs, most computer programs generate the same outputs every time, so they 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 not so easy, but there are ways to make it at least seem nondeterministic. One of them is to use algorithmsthat 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 random.

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:

import random

for i in range(10):    x = random.random()     print x

This program produces the following list of 10 random numbers between 0.0 and up to but not including 1.0.

0.3019270917050.5137870758670.3194704308810.2851459172520.8390690451230.3220270807310.5507221102480.3665916778120.3969814839640.838116437404

Exercise 4.1 Run the program on your system and see what numbers you get.
Run the program more than once and see what numbers you get.

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

>>> random.randint(5, 10)5>>> random.randint(5, 10)9

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

>>> t = [1, 2, 3]>>> random.choice(t)2>>> random.choice(t)3

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