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:
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!