,

Random Number Generator Utilities in JavaScript: Understanding the Statistics Behind

Recently, for our company’s event, I planned to develop a lottery app that will randomly select the winners from the list. So, I immediately built a react application with random number generator code using Math.random() without any second thought and worked on functionality.

// Code for Math.random
return Math.floor(Math.random() * 1000) + 1;

// Code for random-js
const engine = MersenneTwister19937.autoSeed();
const distribution = integer(1, 1000);
return distribution(engine);
FeatureMath.randomrandom-js
SeedingNot possiblepossible
DistributionsUniform onlyDefaults to Uniform, but supports uniform, normal (Gaussian), exponential, and more
For other differences: see this https://www.npmjs.com/package/random-js

Small Sample vs Large Sample Size

Tips to achieve improved randomness and uniformity

  1. Stratified Sampling is dividing the population into sub sections and samples are taken from each sub-section.
  2. Repeating the experiment in same session until we remove any biases and attain expected results
  3. Use of high quality RNGs likes cryptographic-strength algorithms e.g., Mersenne Twister or Xorshift or use crypto.getRandomValues() in JavaScript
  4. Use libraries such as random-js that offer better control instead of Math.random to avoid modular biases

To summarize, achieving perfect uniformity in a small set of random numbers is challenging due to inherent randomness. Utilizing better algorithms, statistical tests, and enhancing the randomness sources can improve uniformity and reduce bias in random number generation.

And wait, though the probability of drawing a number by hand or generating through system is same, the perception of randomness might differ between handpicked numbers (which might be seen as more personal or “lucky”) and numbers generated by a computer algorithm. So, my HRs went with handpicking the winners of lottery.

Feature Image Source: https://www.ultimatesolver.com/en/random-lottery

Sign Up

Can I notify you about future posts ?!

We don’t spam! Read our privacy policy for more info.

NOTE: You will receive confirmation email to explicitly give your consent.

Leave a Reply