linear congruential generator Algorithm

The Linear Congruential Generator (LCG) is a widely used algorithm for generating pseudorandom numbers in computer simulations and cryptography. It is based on a simple mathematical formula that generates a sequence of integers by recursively applying a linear transformation to an initial seed value. The algorithm is highly efficient and easy to implement, which is why it has gained popularity as a standard method for generating random numbers in various applications. The LCG algorithm involves four parameters: a multiplier (a), an increment (c), a modulus (m), and an initial value or seed (X₀). The sequence of pseudorandom numbers is generated by applying the following recurrence relation: Xₙ₊₁ = (aXₙ + c) mod m, for n = 0, 1, 2, ..., where Xₙ is the current number in the sequence, and Xₙ₊₁ is the next number. The modulus (m) determines the range of possible values in the sequence, and the multiplier (a) and increment (c) control the transformation applied to each value. To ensure a long sequence of non-repeating numbers, the choice of these parameters is crucial. The generated sequence will eventually become periodic, with the period length depending on the values of a, c, and m. The careful selection of these parameters can lead to a uniform distribution of numbers and a satisfactory level of pseudorandomness for many practical applications.
__author__ = "Tobias Carryer"

from time import time


class LinearCongruentialGenerator:
    """
    A pseudorandom number generator.
    """

    def __init__(self, multiplier, increment, modulo, seed=int(time())):
        """
        These parameters are saved and used when nextNumber() is called.

        modulo is the largest number that can be generated (exclusive). The most
        efficient values are powers of 2. 2^32 is a common value.
        """
        self.multiplier = multiplier
        self.increment = increment
        self.modulo = modulo
        self.seed = seed

    def next_number(self):
        """
        The smallest number that can be generated is zero.
        The largest number that can be generated is modulo-1. modulo is set in the constructor.
        """
        self.seed = (self.multiplier * self.seed + self.increment) % self.modulo
        return self.seed


if __name__ == "__main__":
    # Show the LCG in action.
    lcg = LinearCongruentialGenerator(1664525, 1013904223, 2 << 31)
    while True:
        print(lcg.next_number())

LANGUAGE:

DARK MODE: