Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Random-Number Generators

Pseudo-random number generators (PRNGs) are algorithms that produce sequences of numbers that approximate the properties of random numbers. They are deterministic, meaning that if you know the initial state (or seed) of the generator, you can predict the entire sequence of numbers it will produce. However, they are designed to be statistically indistinguishable from true random numbers for most applications.

Linear Congruential Generator (LCG)

The Linear Congruential Generator is one of the oldest and simplest PRNGs. It uses a linear equation to generate the next number in the sequence based on the current number. The formula is:

Xn+1=(a×Xn+c)modmX_{n+1} = (a \times X_n + c) \mod m

Implementation of LCG

def linear_congruential_generator(seed, a, c, m, num_values=1):
    random_numbers = []

    for _ in range(num_values):
        seed = (a * seed + c) % m
        random_numbers.append(seed/m)  # Normalize to [0, 1]
    
    return random_numbers

linear_congruential_generator(seed=1, a=1664525, c=1013904223, m=2**32, num_values=5)
[0.23645552527159452, 0.3692706737201661, 0.5042420323006809, 0.7048832636792213, 0.05054362863302231]

Plot

import matplotlib.pyplot as plt

plt.hist(
    linear_congruential_generator(
        seed=1, a=1664525, c=1013904223, m=2**32, num_values=10000
    ),
    color="skyblue",
    edgecolor="black",
    bins=50,
)
plt.title("Histogram of LCG-generated Random Numbers")
plt.xlabel("Value")
plt.ylabel("Frequency")
<Figure size 640x480 with 1 Axes>