How Random Numbers are Generated

Sh Raj - Jul 23 - - Dev Community

Understanding Random Number Generation

Random numbers play a crucial role in various fields such as simulations, cryptography, statistical sampling, and more. This article delves into how random numbers are generated, focusing on two popular programming languages: JavaScript and Python.

Pseudorandom Number Generators (PRNGs)

Most programming languages use pseudorandom number generators (PRNGs) to produce random numbers. PRNGs use mathematical algorithms to generate sequences of numbers that appear random. These numbers are not truly random because they are determined by an initial value known as a seed. However, they are sufficient for many applications.

Characteristics of PRNGs

  1. Deterministic: Given the same seed, a PRNG will always produce the same sequence of numbers.
  2. Periodicity: PRNGs will eventually repeat their sequence of numbers after a certain period.
  3. Speed: PRNGs are generally fast and efficient.

JavaScript: Math.random()

JavaScript's Math.random() function is commonly used to generate random numbers. The exact algorithm used by Math.random() can vary between different JavaScript engines, but a widely used algorithm is the Mersenne Twister.

How Math.random() Works

The Mersenne Twister is known for its long period and high-quality randomness. Here is a simplified example of how the Mersenne Twister algorithm can be implemented in JavaScript:

class MersenneTwister {
  constructor(seed) {
    if (seed === undefined) {
      seed = new Date().getTime();
    }
    this.mt = new Array(624);
    this.index = 0;
    this.mt[0] = seed;
    for (let i = 1; i < 624; i++) {
      this.mt[i] = (0x6c078965 * (this.mt[i - 1] ^ (this.mt[i - 1] >> 30)) + i) >>> 0;
    }
  }

  generate() {
    if (this.index === 0) {
      this.twist();
    }
    let y = this.mt[this.index];
    y = y ^ (y >> 11);
    y = y ^ ((y << 7) & 0x9d2c5680);
    y = y ^ ((y << 15) & 0xefc60000);
    y = y ^ (y >> 18);
    this.index = (this.index + 1) % 624;
    return y / 0xffffffff;
  }

  twist() {
    for (let i = 0; i < 624; i++) {
      const y = (this.mt[i] & 0x80000000) + (this.mt[(i + 1) % 624] & 0x7fffffff);
      this.mt[i] = this.mt[(i + 397) % 624] ^ (y >> 1);
      if (y % 2 !== 0) {
        this.mt[i] = this.mt[i] ^ 0x9908b0df;
      }
    }
  }
}

// Example usage:
const mt = new MersenneTwister(12345); // Seed value
const randomNumber = mt.generate(); // Get a random number
console.log(randomNumber);
Enter fullscreen mode Exit fullscreen mode

This code demonstrates a simplified version of the Mersenne Twister algorithm used to generate random numbers.

Using Math.random()

In JavaScript, you can generate a random number between 0 (inclusive) and 1 (exclusive) using Math.random():

const randomNumber = Math.random();
console.log(randomNumber);
Enter fullscreen mode Exit fullscreen mode

Python: random Module

Python provides the random module, which includes various functions to generate random numbers. The default PRNG algorithm used by Python's random module is also the Mersenne Twister.

How to Use Python's random Module

Here are some examples of generating random numbers in Python:

import random

# Generate a random float between 0.0 and 1.0
random_float = random.random()
print(random_float)

# Generate a random integer between 1 and 100
random_int = random.randint(1, 100)
print(random_int)

# Generate a random number from a normal distribution with mean 0 and standard deviation 1
random_normal = random.gauss(0, 1)
print(random_normal)
Enter fullscreen mode Exit fullscreen mode

Seeding the Random Number Generator

To ensure reproducibility, you can seed the random number generator in Python:

import random

# Seed the random number generator
random.seed(12345)

# Generate random numbers
print(random.random())
print(random.randint(1, 100))
Enter fullscreen mode Exit fullscreen mode

Using the same seed value will produce the same sequence of random numbers every time you run the program.

Conclusion

Random number generation is a fundamental concept with a wide range of applications. While the numbers generated by Math.random() in JavaScript and the random module in Python are not truly random, they are sufficiently random for most practical purposes. Understanding how these generators work and how to use them effectively is crucial for developers and researchers alike.


This article provides a basic overview of how random numbers are generated in JavaScript and Python, along with practical examples of using Math.random() and Python's random module.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .