← Back to the lab

Random Number Generation

By Miguel F. Serna

In 2023, I wrote a 4,000-word computer science research paper comparing the pseudorandom number generators used by Python and JavaScript.

Read the full paper.

The question

Python's random module uses MT19937, better known as the Mersenne Twister. JavaScript engines commonly use Xorshift128+ for Math.random(). I wanted to understand how each algorithm worked and which one produced better random numbers.

How I tested them

I generated one billion integers with each generator and used a chi-square goodness-of-fit test to compare their distributions. I then ran both output streams through PractRand to look for correlations and patterns that the distribution test could not detect.

What I found

Both generators passed the chi-square test. Their outputs had similarly uniform distributions, but PractRand exposed a large difference. Xorshift128+ failed after 256 megabytes of data, while MT19937 reached 256 gigabytes before failing.

Xorshift128+ was substantially faster. MT19937 produced statistically stronger output in my tests. The useful answer depended on the job: speed suited JavaScript's common browser workloads, while Python's generator offered a stronger general-purpose balance.