on the prng behind random.random()

Robert Girault r at dev.null
Mon Nov 19 15:26:11 EST 2018


Peter Otten <__peter__ at web.de> writes:

> Robert Girault wrote:
>
>> Looking at its source code, it seems the PRNG behind random.random() is
>> Mersenne Twister, but I'm not sure.  It also seems that random.random()
>> is using /dev/urandom.  Can someone help me to read that source code?
>> 
>> I'm talking about CPython, by the way.  I'm reading
>> 
>>   https://github.com/python/cpython/blob/master/Lib/random.py
>> 
>> The initial comment clearly says it's Mersenne Twister, but the only
>> random() function there seems to call _urandom(), which I suppose is an
>> interface to /dev/urandom.
>> 
>> What am I missing here?
>
> There's a class random.Random which is instantiated at the end of the file, 
> and random() is bound to the corresponding method:
>
> _inst = Random()
> ...
> random = _inst.random
>
> The Random class inherits from _random.Random [...]

Thanks.  I missed that.

> which is implemented in C and does most of the actual work. If you can
> read C:
>
> https://github.com/python/cpython/blob/master/Modules/_randommodule.c
>
> The most relevant part seems to be genrand_int32() which is wrapped by 
> random_random() that actually implenents the _random.Random.random() method.

Nice.  So Python's random.random() does indeed use mt19937.  Since it's
been broken for years, why isn't it replaced by something newer like
ChaCha20?  Is it due to backward compatibility?  That would make sense.

Do you know who broke mt19937 and when?  I'd love to read the reference.
Thank you!



More information about the Python-list mailing list