Mersenne Twister Random Generator

De Augusto Baffa Wiki
Ir para navegação Ir para pesquisar
Esta página é uma versão traduzida da página Gerador Aleatório Mersenne Twister. Sua tradução está 100% completa.
Outros idiomas:
English • ‎português do Brasil

The Mersenne Twister is a PRNG developed in 1997 by Makoto Matsumoto and Takuji Nishimura. It provides for fast generation of very high quality pseudorandom integers. The Mersenne Twister was designed specifically to address many of the flaws found in older algorithms. (Matsumoto, 1998)


The Mersenne Twister is a very popular PRNG. It is the “built in” PRNG for Ruby, Python, and R. This book’s examples also contain implementations for other languages. The Mersenne Twister algorithm creates high quality random numbers suitable for Monte Carlo simulations. Mersenne Twister is not a cryptographically secure generator. However, its execution speed and high quality randomness make it a very attractive generator for AI.


The name Mersenne Twister comes from the fact that that the period of the Mersenne Twister is always chosen to be a Mersenne prime number.


A prime number is any number that can only be divided evenly by itself and one. For example, 5 is a prime number. A Mersenne prime number is any number n where M is also a prime number, as seen in Equation below.

[math]M_n = 2 ^ n - 1[/math]

Sample Python Code

1 million attempts sample
def mersenne_twister(mult=16807,mod=(2**31)-1,period=(2**30),min=0,max=1,seed=123456789, size=1):
    """Pseudorandom number generater"""
    MT = []
    
    for i in range(size):
        seed = (mult * seed) % mod
        MT.append( (max - min) * (seed / mod) + min )
        period -= 1
    
    if period == 0:
            print("Pseudorandom period nearing!!")
    
    if size == 1:
        return MT.pop()
    else:
        return MT