Seedable JavaScript random number generator

前端 未结 9 814
暖寄归人
暖寄归人 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:20

    If you want to be able to specify the seed, you just need to replace the calls to getSeconds() and getMinutes(). You could pass in an int and use half of it mod 60 for the seconds value and the other half modulo 60 to give you the other part.

    That being said, this method looks like garbage. Doing proper random number generation is very hard. The obvious problem with this is that the random number seed is based on seconds and minutes. To guess the seed and recreate your stream of random numbers only requires trying 3600 different second and minute combinations. It also means that there are only 3600 different possible seeds. This is correctable, but I'd be suspicious of this RNG from the start.

    If you want to use a better RNG, try the Mersenne Twister. It is a well tested and fairly robust RNG with a huge orbit and excellent performance.

    EDIT: I really should be correct and refer to this as a Pseudo Random Number Generator or PRNG.

    "Anyone who uses arithmetic methods to produce random numbers is in a state of sin."
                                                                                                                                                              --- John von Neumann

提交回复
热议问题