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

How Can I Seed the Random Number Generator in JavaScript?

DDD
Release: 2024-11-29 17:35:12
Original
275 people have browsed it

How Can I Seed the Random Number Generator in JavaScript?

Seeding the Random Number Generator in JavaScript

Introduction:
JavaScript's built-in random number generator, Math.random(), cannot be explicitly seeded or manipulated. However, external functions can be used to provide seeding functionality and generate high-quality random numbers with specific initial conditions.

Answer:
While Math.random() remains unseedable, several efficient and robust Pseudorandom Number Generator (PRNG) functions exist in JavaScript that can be seeded and provide excellent randomness.

Seed Initialization:
To initialize PRNGs properly, it is crucial to utilize high entropy seeds. One effective method is to use hash functions like cyrb128, which can generate diverse 128-bit hash values from input strings. Alternatively, padding the seed with dummy data and advancing the generator can also be employed, although it limits the number of initial states.

sfc32 (Simple Fast Counter) PRNG:
sfc32 is a notable PRNG that has successfully passed the PractRand random number testing suite. It operates with a 128-bit state and delivers exceptional speed in JavaScript. An example of using sfc32 with a custom seed generator:

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;
  }
}

const seedgen = () => (Math.random() * 2 ** 32) >>> 0;
const getRand = sfc32(seedgen(), seedgen(), seedgen(), seedgen());
for (let i = 0; i < 10; i++) console.log(getRand());
Copy after login

Utilizing these techniques, JavaScript developers can harness the power of seedable PRNGs to generate high-quality random numbers for various applications, ranging from simulation to game development.

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template