The Python Oracle

Python large random integers and the precision of the Mersenne Twister

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands

--

Chapters
00:00 Question
01:46 Accepted answer (Score 4)
02:32 Answer 2 (Score 4)
03:14 Thank you

--

Full question
https://stackoverflow.com/questions/1170...

Answer 1 links:
[here]: http://hg.python.org/cpython/file/4e85e4...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #random #precision

#avk47



ANSWER 1

Score 4


53 bits is not an inherent limit in the generator, it is the amount that Python returns when you request a float, since floats have 53 bits of precision.

You can get random integers directly using stuff like random.getrandbits.

In more detail, the Mersenne Twister used in CPython generates 32 bits at a time. The module code calls this twice and combines the results to generate a 53 bit float. If you call getrandbits, it will call the internal function as many times as necessary to generate k bits. The code for this can be found in here.




ACCEPTED ANSWER

Score 4


What Python does is generate 64 bits of randomness from calling the 32-bit version of MT19937 twice, but since that number is constrained to [0.0, 1.0) the result is constrained to 53 bits of precision (limitation of floating-point format).

Python random.py is capable of pulling bits from /dev/urandom or Windows CryptGenRandom (if supported), if you use the random.SystemRandom class. Otherwise, it generates larger numbers by pulling successive bits from repeated calls to MT19937.