tc39 / proposal-seeded-random

Proposal for an options argument to be added to JS's Math.random() function, and some options to start it with.
MIT License
156 stars 6 forks source link

Allow seeding from another random source #11

Closed davidje13 closed 5 years ago

davidje13 commented 5 years ago

A common (in my experience) requirement for seeded random generators is the ability to seed sub-generators. Among other things, this allows a single master seed to create many random sources which can be used for different parts of a simulation independently (e.g. one for terrain height-maps, one for cloud generation, one for AI, etc.).

Sub-generators are not created with the same seed as their parent (as this would make all generators identical), but rather with a random value chosen by the parent. With the current API, the required code would be:

const MAX_SEED = ????;
const parent = Math.seededPRNG({seed:0});
const child = Math.seededPRNG({seed: parent.next().value * MAX_SEED});

But this will not give access to the full range of possible seeds due to numeric precision. A better option would be to populate a typed array with values and use that as a seed, but this is very verbose.

Please make it possible to pass an existing PRNG as a seed for a new PRNG:

const parent = Math.seededPRNG({seed:0});
const child = Math.seededPRNG({seed: parent});

This is distinct from the proposed API for cloning a PRNG:

const parent = Math.seededPRNG({seed:0});
const child = Math.seededPRNG({seed: parent.seed()});

But could cause some confusion due to the similarity.

tabatkins commented 5 years ago

Agreed, this is a good idea. I've added a .randomSeed() method to generate a pseudorandom seed value (rather than a number in the [0,1) range).