Home >Web Front-end >JS Tutorial >How Can I Seed Random Number Generators in JavaScript?

How Can I Seed Random Number Generators in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 06:24:14592browse

How Can I Seed Random Number Generators in JavaScript?

Seeding the Random Number Generator in JavaScript

The built-in Math.random() in JavaScript does not provide the ability to seed the random number generator, meaning that it cannot be initialized with a specific value to generate a predetermined sequence of random numbers.

While seeding is not possible with Math.random(), there are external libraries and implementations that offer custom functions for generating seedable pseudorandom numbers. Here are a few options:

Pseudorandom Number Generator (PRNG) Functions

Several compact and efficient PRNG functions can be implemented in JavaScript, providing high-quality random numbers that can be seeded with one or more 32-bit numbers.

Seed Initialization

It is crucial to initialize your PRNGs properly to avoid low-entropy seeds that can affect the randomness of the generated numbers. Here are two common methods:

  • Hash Functions: Hash functions can generate seeds from short strings, allowing you to use a string as a seed. For instance, the cyrb128 hash function can produce a 128-bit hash value from a string.
  • Dummy Data Padding: Alternatively, you can pad the seed with dummy data and advance the generator a few times to mix the initial state thoroughly.

PRNG Algorithms

Here's an example of the sfc32 (Simple Fast Counter) algorithm, which has a 128-bit state and produces random numbers in the range 0-1:

function sfc32(a, b, c, d) {
  return function() {
    a |= 0; b |= 0; c |= 0; d |= 0;
    let t = (a + b | 0) + d | 0;
    d = d + 1 | 0;
    a = b ^ b >>> 9;
    b = c + (c << 3) | 0;
    c = (c << 21 | c >>> 11);
    c = c + t | 0;
    return (t >>> 0) / 4294967296;
  }
}

The above is the detailed content of How Can I Seed Random Number Generators in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn