// Found this seed-based random generator somewhere
// Based on The Central Randomizer 1.3 (C) 1997 by Paul Houle (houle@msc.cornell.edu)
var seed = 1;
/**
* return a random number based on a seed
* @param seed
* @returns {number}
*/
function getNextValue() {
seed = (seed * 9301 + 49297) % 233280;
return seed/(233280.0);
}
function setSeed(_seed_) {
seed = _seed_;
}
module.exports = {
nextValue: getNextValue,
seed: setSeed
};Run Code Online (Sandbox Code Playgroud)
见https://github.com/dylang/shortid/blob/master/lib/random/random-from-seed.js
\n\n\n为什么要
\n(seed * 9301 + 49297) % 233280 / 233280.0生成随机数?
事实并非如此。它生成一个完全确定的数字。乍一看,结果序列可能看起来是随机的,因此这是一个伪随机生成器。更准确地说,它是一个线性同余发生器。
\n\n你说你对“神奇”的数字感到好奇。嗯,它们实际上大多是从几乎无限的数字集中任意选择的。通常,出于数论原因(主要是为了避免生成的模式中出现非常明显的重复),使用质数系数(特别是作为除数);然而,像这样的朴素 LCG 会产生非常低质量的 PRN,因此如果确实需要高质量的伪随机性,尝试调整 LCG \xe2\x80\x93 是毫无意义的,只需使用更好的PRNG 算法。
\n