For quantitative applications such as numerical simulations, it is convenient to have full control over the Pseudo-Random Number Generator we choose to use. For this reason, I implemented my own version of the Linear Congruential Generator (LCG), a simple and reliable algorithm.
An LCG is a method for generating real non-negative pseudo-random numbers from the uniform distribution on
First, an LCG produces a sequence of non-negative integers called states according to the recurring relation
Where
-
$m > 0$ is the modulus; mod m stands for "modulo m", which means you divide by m and take the remainder. -
$x_i = \{0, 1, ..., m - 1\}$ is the i-th state of the generator -
$x_0 = \{0, 1, ..., m - 1\}$ is a non-negative integer constant called seed. The seed is the initial state of the generator -
$a = \{0, 1, ..., m - 1\}$ is a non-negative integer constant called multiplier -
$c = \{0, 1, ..., m - 1\}$ is a non-negative integer constant called increment
The integer constants m, a, c and x_0 specify the generator.
For each state generated by the LCG, we can take
Where
This small project explores a simple implementation of the LCG as a Python generator. All the code is contained in the lcg.py
file and is pretty straightforward.
A detailed list of good values for the LCG constants m
and a
can be found at:
L’ecuyer, Pierre. "Tables of linear congruential generators of different sizes and good lattice structure." Mathematics of Computation 68.225 (1999): 249-260.