Wednesday, June 1, 2016

The many uses of randomness

By Vasudev Ram

Dice image attribution

Computer random number generators (RNGs) [1] have many uses. In a programming class I was teaching recently, a participant was surprised by a certain usage of random numbers that I showed; which I thought would be common knowledge. That made me realize that many novices, and possibly even some more experienced programmers, may not be aware of some among the many useful applications of random numbers.

That gave me the idea for this post, in which I'll show some of the ways in which random numbers are useful. The examples are in Python, but the concepts and techniques can be applied in any programming language that
has a random number generation facility.

[1] Strictly speaking, these are really pseudo-random number generators (PRNGs), but I'll call them RNGs for short.

(The Wikipedia article on random number generation has information on the difference between RNGs and PRNGs - and a lot more interesting information on random numbers in general, including their use in ancient times, e.g. the use of yarrow stalks (for divination) in the I Ching :)

Note: None of the random number uses that I will show requires advanced mathematical knowledge.

Let's start.

Import and introspect the random module from Python's standard library:
$ python
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'System
Random', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__'
, '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_c
eil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_ra
ndom', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betava
riate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbi
ts', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate'
, 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'tr
iangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
We can see that the module has many functions and other attributes, such as the important mathematical constants e (_e) and pi (_pi). (Those last two are also available in the math module as e and pi.)

In this post, I'll look at some uses of one of the most fundamental functions in the module, called random(), like the module. In a following post or two, I'll look at other functions, and also other uses in different areas, including some less obvious ones.

First print its docstring:
>>>print random.random.__doc__
random() -> x in the interval [0, 1).
It returns a random float value in the half-closed interval [0, 1), which means, any x, such that 0.0 <= x < 1.0.

Here is a program,, that shows some uses of the random() function:
from __future__ import print_function

# A program showing various uses of the "random" function 
# from the "random" module of Python's standard library.
# Author: Vasudev Ram -
# Copyright 2016 Vasudev Ram

from random import random
from random import getstate, setstate

print("Ex. 1. Plain calls to random():")
print("Gives 10 random float values in the interval [0, 1).")
for i in range(10):


print("Ex. 2. Calls to random() scaled by 10:")
print("Gives 10 random float values in the interval [0, 10).")
for i in range(10):
    print(10.0 * random())


print("Ex. 3. Calls to random() scaled by 10 and offset by -5:")
print("Gives 10 random float values in the interval [-5, 5).")
for i in range(10):
    print(10.0 * random() - 5.0)


print("Ex. 4. Calls to random() scaled by 20 and offset by 40:")
print("Gives 10 random float values in the interval [40, 60).")
for i in range(10):
    print(20.0 * random() + 40.0)
Here is the program's output when run with:
Ex. 1. Plain calls to random():
Gives 10 random float values in the interval [0, 1).

Ex. 2. Calls to random() scaled by 10:
Gives 10 random float values in the interval [0, 10).

Ex. 3. Calls to random() scaled by 10 and offset by -5:
Gives 10 random float values in the interval [-5, 5).

Ex. 4. Calls to random() scaled by 20 and offset by 40:
Gives 10 random float values in the interval [40, 60).
It shows how to scale and offset the values you get from random(), to transform them from the range of 0 to 1, to other ranges.

Notice that the values of the random numbers in the four sets of output are all different, even if you take the scaling into account. For example, the numbers in the second set of output are not the same as the numbers in the first set multiplied by 10, even though that is what we do in code for the second set. The reason for this is that the random numbers generated, cycle through a very long sequence, and so the first 10 numbers are output in set 1, the second 10 in set 2, and so on.

What if we wanted to have the same values of random numbers (except for the differences caused by scaling and offsetting) in all 4 output sets, say for the sake of some sort of consistency or repeatability in some scientific or statistical experiment? One obvious way is to save the first 10 numbers generated in the first snippet (say in a list) and use them in the following 3 snippets.

There is another way to do it, with the getstate() and setstate() functions of the module.

Put this line:
state = random.getstate()
before the snippet (Ex. 1.) that generates the first set of output.

Then put this line:
before each of the following three snippets (Ex. 2 to 4.). That will do it, since now the same 10 random numbers will be generated by each snippet (before taking into account the scaling and offsetting).

In the next post, I'll show some other uses of random numbers, such for doing things with strings.

See also:

Pseudo-random number generator
Hardware random number_generator

The picture below, from Wikipedia, is the title page of a Song dynasty (c. 1100) edition of the I Ching.

I Ching image attribution

print ['Enjoy', 'See you soon', 'Bye for now'][randint(0, 2)] + " :)"

- Vasudev Ram - Online Python training and consulting

Signup to hear about my new courses and products.

My Python posts     Subscribe to my blog by email

My ActiveState recipes

No comments: