A goal of this repository is to analyze the distribution of different pseudo-random number generation methods in plain JavaScript.
While developing a Phaser video game I needed to randomly place objects in a 2D space. Despite the documentation of Math.random()
stating it's a 'approximately uniform distribution' 1, results looked awfully similar to a normal distribution (objects were generated mostly in the middle of the screen). I decided to investigate the issue and test Math.random()
, as well as other pseudo-random number generators.
A random 1.000.000 numbers ([0, 1]) are generated using each method and saved in a CSV file. Results are then processed by pandas and matplotlib to generate a histogram and calculate a standard deviation. Tests were performed on an Apple M1 MacBook Air with 8GB of RAM and Node.js v20.3.0.
The Math.random()
static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user. 1
Standard Deviation: 0.28883
A linear congruential generator (LCG) is an algorithm that yields a sequence of pseudo-randomized numbers calculated with a discontinuous piecewise linear equation. The method represents one of the oldest and best-known pseudorandom number generator algorithms. 2
RANDU is a linear congruential pseudorandom number generator, defined by the recurrence 3:
Standard Deviation: 0.28847
A counter-based random number generation (CBRNG, also known as a counter-based pseudo-random number generator, or CBPRNG) is a kind of pseudorandom number generator that uses only an integer counter as its internal state. They are generally used for generating pseudorandom numbers for large parallel computations. 4
This implementation is based on the paper 5 by Sebastiano Vigna and is available as a npm package 6. GitHub page of the project 7.
Standard Deviation: 0.28855