Seedable JavaScript random number generator

前端 未结 9 804
暖寄归人
暖寄归人 2020-11-22 10:13

The JavaScript Math.random() function returns a random value between 0 and 1, automatically seeded based on the current time (similar to Java I believe). However, I don\'t

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 10:25

    The following is a PRNG that may be fed a custom seed. Calling SeedRandom will return a random generator function. SeedRandom can be called with no arguments in order to seed the returned random function with the current time, or it can be called with either 1 or 2 non-negative inters as arguments in order to seed it with those integers. Due to float point accuracy seeding with only 1 value will only allow the generator to be initiated to one of 2^53 different states.

    The returned random generator function takes 1 integer argument named limit, the limit must be in the range 1 to 4294965886, the function will return a number in the range 0 to limit-1.

    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

    Example use:

    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.
    

    This generator exhibit the following properties:

    • It has approximately 2^64 different possible inner states.
    • It has a period of approximately 2^63, plenty more than anyone will ever realistically need in a JavaScript program.
    • Due to the mod values being primes there is no simple pattern in the output, no matter the chosen limit. This is unlike some simpler PRNGs that exhibit some quite systematic patterns.
    • It discards some results in order to get a perfect distribution no matter the limit.
    • It is relatively slow, runs around 10 000 000 times per second on my machine.

提交回复
热议问题