Seedable JavaScript random number generator
JavaScript EDOCX1·0函数返回0到1之间的随机值,根据当前时间自动播种(类似于Java I相信)。然而,我认为没有任何方法可以让你自己为它播种。
如何制作一个随机数生成器,我可以为其提供自己的种子值,以便让它生成(伪)随机数的可重复序列?
其中一个选项是http://davidbu.com/seedrandom,它是一个基于rc4的seedable math.random()drop,用nice属性替换。
如果您不需要播种功能,只需使用
我不知道你在使用什么RNG,但最好知道它并记录下来,这样你就知道它的特点和局限性。
正如斯塔克II所说,梅森缠绕机是一个很好的prng,但它不容易实施。如果你想自己去做,试着实现一个LCG——它非常简单,具有相当好的随机性(不如Mersenne Twister),并且你可以使用一些流行的常量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | function RNG(seed) { // LCG using GCC's constants this.m = 0x80000000; // 2**31; this.a = 1103515245; this.c = 12345; this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1)); } RNG.prototype.nextInt = function() { this.state = (this.a * this.state + this.c) % this.m; return this.state; } RNG.prototype.nextFloat = function() { // returns in range [0,1] return this.nextInt() / (this.m - 1); } RNG.prototype.nextRange = function(start, end) { // returns in range [start, end): including start, excluding end // can't modulu nextInt because of weak randomness in lower bits var rangeSize = end - start; var randomUnder1 = this.nextInt() / this.m; return start + Math.floor(randomUnder1 * rangeSize); } RNG.prototype.choice = function(array) { return array[this.nextRange(0, array.length)]; } var rng = new RNG(20); for (var i = 0; i < 10; i++) console.log(rng.nextRange(10, 50)); var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; for (var i = 0; i < 10; i++) console.log(rng.choice(digits)); |
如果您想指定种子,只需替换对
尽管如此,这个方法看起来像垃圾。要正确生成随机数是非常困难的。这明显的问题是随机数种子是基于秒和分钟的。要猜测种子并重新创建随机数流,只需要尝试3600种不同的秒和分钟组合。这也意味着只有3600种可能的种子。这是可以纠正的,但我从一开始就怀疑这个RNG。
如果你想使用更好的RNG,试试梅森缠绕机。这是一个经过良好测试和相当强大的RNG具有巨大的轨道和出色的性能。
编辑:我真的应该是正确的,把它称为伪随机数生成器或prng。
"Anyone who uses arithmetic methods to produce random numbers is in a state of sin."
--- John von Neumann
我使用了mersenne twister的javascript端口:网址:https://gist.github.com/300494它允许您手动设置种子。另外,正如其他答案中提到的,旋转木马是一个非常好的prng。
您列出的代码有点像Lehmer RNG。如果是这种情况,那么
如果这是真的,你可以修改
以下是一个可以喂入自定义种子的prng。调用
返回的随机生成器函数接受名为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function SeedRandom(state1,state2){ var mod1=4294967087 var mul1=65539 var mod2=4294965887 var mul2=65537 if(typeof state1!="number"){ state1=+new Date() } if(typeof state2!="number"){ state2=state1 } state1=state1%(mod1-1)+1 state2=state2%(mod2-1)+1 function random(limit){ state1=(state1*mul1)%mod1 state2=(state2*mul2)%mod2 if(state1<limit && state2<limit && state1<mod1%limit && state2<mod2%limit){ return random(limit) } return (state1+state2)%limit } return random } |
示例用法:
1 2 3 4 5 | var generator1=SeedRandom() //Seed with current time var randomVariable=generator1(7) //Generate one of the numbers [0,1,2,3,4,5,6] var generator2=SeedRandom(42) //Seed with a specific seed var fixedVariable=generator2(7) //First value of this generator will always be //1 because of the specific seed. |
号
该发生器具有以下特性:
- 它有大约2^64种不同的内部状态。
- 它的周期约为2^63,比任何人在JavaScript程序中实际需要的时间都多。
- 由于
mod 值是素数,因此无论选择的限制是什么,输出中都没有简单的模式。这与一些简单的prng不同,prng显示了一些相当系统的模式。 - 它抛弃了一些结果,以得到一个完美的分布,无论是极限。
- 它比较慢,在我的机器上每秒运行10000次左右。
如果您使用typescript编程,我将引入Christoph Henkelmann对此线程的答案的mersenne twister实现改编为typescript类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | /** * copied almost directly from Mersenne Twister implementation found in https://gist.github.com/banksean/300494 * all rights reserved to him. */ export class Random { static N = 624; static M = 397; static MATRIX_A = 0x9908b0df; /* constant vector a */ static UPPER_MASK = 0x80000000; /* most significant w-r bits */ static LOWER_MASK = 0x7fffffff; /* least significant r bits */ mt = new Array(Random.N); /* the array for the state vector */ mti = Random.N + 1; /* mti==N+1 means mt[N] is not initialized */ constructor(seed:number = null) { if (seed == null) { seed = new Date().getTime(); } this.init_genrand(seed); } private init_genrand(s:number) { this.mt[0] = s >>> 0; for (this.mti = 1; this.mti < Random.N; this.mti++) { var s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30); this.mt[this.mti] = (((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253) + this.mti; /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ this.mt[this.mti] >>>= 0; /* for >32 bit machines */ } } /** * generates a random number on [0,0xffffffff]-interval * @private */ private _nextInt32():number { var y:number; var mag01 = new Array(0x0, Random.MATRIX_A); /* mag01[x] = x * MATRIX_A for x=0,1 */ if (this.mti >= Random.N) { /* generate N words at one time */ var kk:number; if (this.mti == Random.N + 1) /* if init_genrand() has not been called, */ this.init_genrand(5489); /* a default initial seed is used */ for (kk = 0; kk < Random.N - Random.M; kk++) { y = (this.mt[kk] & Random.UPPER_MASK) | (this.mt[kk + 1] & Random.LOWER_MASK); this.mt[kk] = this.mt[kk + Random.M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < Random.N - 1; kk++) { y = (this.mt[kk] & Random.UPPER_MASK) | (this.mt[kk + 1] & Random.LOWER_MASK); this.mt[kk] = this.mt[kk + (Random.M - Random.N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (this.mt[Random.N - 1] & Random.UPPER_MASK) | (this.mt[0] & Random.LOWER_MASK); this.mt[Random.N - 1] = this.mt[Random.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; this.mti = 0; } y = this.mt[this.mti++]; /* Tempering */ y ^= (y >>> 11); y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= (y >>> 18); return y >>> 0; } /** * generates an int32 pseudo random number * @param range: an optional [from, to] range, if not specified the result will be in range [0,0xffffffff] * @return {number} */ nextInt32(range:[number, number] = null):number { var result = this._nextInt32(); if (range == null) { return result; } return (result % (range[1] - range[0])) + range[0]; } /** * generates a random number on [0,0x7fffffff]-interval */ nextInt31():number { return (this._nextInt32() >>> 1); } /** * generates a random number on [0,1]-real-interval */ nextNumber():number { return this._nextInt32() * (1.0 / 4294967295.0); } /** * generates a random number on [0,1) with 53-bit resolution */ nextNumber53():number { var a = this._nextInt32() >>> 5, b = this._nextInt32() >>> 6; return (a * 67108864.0 + b) * (1.0 / 9007199254740992.0); } } |
您可以如下使用它:
1 2 3 4 | var random = new Random(132); random.nextInt32(); //return a pseudo random int32 number random.nextInt32([10,20]); //return a pseudo random int in range [10,20] random.nextNumber(); //return a a pseudo random number in range [0,1] |
。
检查源以了解更多方法。
Note: This code was originally included in the question above. In the interests of keeping the question short and focused, I've moved it to this Community Wiki answer.
我发现这段代码很流行,它似乎可以很好地得到一个随机数,然后使用种子,但我不太确定逻辑是如何工作的(例如,2345678901、48271和2147483647数字来自何处)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | function nextRandomNumber(){ var hi = this.seed / this.Q; var lo = this.seed % this.Q; var test = this.A * lo - this.R * hi; if(test > 0){ this.seed = test; } else { this.seed = test + this.M; } return (this.seed * this.oneOverM); } function RandomNumberGenerator(){ var d = new Date(); this.seed = 2345678901 + (d.getSeconds() * 0xFFFFFF) + (d.getMinutes() * 0xFFFF); this.A = 48271; this.M = 2147483647; this.Q = this.M / this.A; this.R = this.M % this.A; this.oneOverM = 1.0 / this.M; this.next = nextRandomNumber; return this; } function createRandomNumber(Min, Max){ var rand = new RandomNumberGenerator(); return Math.round((Max-Min) * rand.next() + Min); } //Thus I can now do: var letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; var numbers = ['1','2','3','4','5','6','7','8','9','10']; var colors = ['red','orange','yellow','green','blue','indigo','violet']; var first = letters[createRandomNumber(0, letters.length)]; var second = numbers[createRandomNumber(0, numbers.length)]; var third = colors[createRandomNumber(0, colors.length)]; alert("Today's show was brought to you by the letter:" + first +", the number" + second +", and the color" + third +"!"); /* If I could pass my own seed into the createRandomNumber(min, max, seed); function then I could reproduce a random output later if desired. */ |
好的,这是我确定的解决方案。
首先,使用"newseed()"函数创建种子值。然后将seed值传递给"srandom()"函数。最后,"srandom()"函数返回一个介于0和1之间的伪随机值。
关键的一点是种子值存储在一个数组中。如果它只是一个整型或浮点型,那么每次调用函数时,该值都会被覆盖,因为整型、浮点型、字符串等的值直接存储在堆栈中,而不是像数组和其他对象那样只存储指针。因此,种子的价值可以保持持久。
最后,可以定义"srandom()"函数,使其成为"math"对象的一种方法,但我将由您来决定。;)
祝你好运!
JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | // Global variables used for the seeded random functions, below. var seedobja = 1103515245 var seedobjc = 12345 var seedobjm = 4294967295 //0x100000000 // Creates a new seed for seeded functions such as srandom(). function newseed(seednum) { return [seednum] } // Works like Math.random(), except you provide your own seed as the first argument. function srandom(seedobj) { seedobj[0] = (seedobj[0] * seedobja + seedobjc) % seedobjm return seedobj[0] / (seedobjm - 1) } // Store some test values in variables. var my_seed_value = newseed(230951) var my_random_value_1 = srandom(my_seed_value) var my_random_value_2 = srandom(my_seed_value) var my_random_value_3 = srandom(my_seed_value) // Print the values to console. Replace"WScript.Echo()" with"alert()" if inside a Web browser. WScript.Echo(my_random_value_1) WScript.Echo(my_random_value_2) WScript.Echo(my_random_value_3) |
Lua 4(我的个人目标环境):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | -- Global variables used for the seeded random functions, below. seedobja = 1103515.245 seedobjc = 12345 seedobjm = 4294967.295 --0x100000000 -- Creates a new seed for seeded functions such as srandom(). function newseed(seednum) return {seednum} end -- Works like random(), except you provide your own seed as the first argument. function srandom(seedobj) seedobj[1] = mod(seedobj[1] * seedobja + seedobjc, seedobjm) return seedobj[1] / (seedobjm - 1) end -- Store some test values in variables. my_seed_value = newseed(230951) my_random_value_1 = srandom(my_seed_value) my_random_value_2 = srandom(my_seed_value) my_random_value_3 = srandom(my_seed_value) -- Print the values to console. print(my_random_value_1) print(my_random_value_2) print(my_random_value_3) |