Seeding the random number generator in Javascript

后端 未结 13 1400
野趣味
野趣味 2020-11-22 09:28

Is it possible to seed the random number generator (Math.random) in Javascript?

相关标签:
13条回答
  • 2020-11-22 10:33

    NOTE: Despite (or rather, because of) succinctness and apparent elegance, this algorithm is by no means a high-quality one in terms of randomness. Look for e.g. those listed in this answer for better results.

    (Originally adapted from a clever idea presented in a comment to another answer.)

    var seed = 1;
    function random() {
        var x = Math.sin(seed++) * 10000;
        return x - Math.floor(x);
    }
    

    You can set seed to be any number, just avoid zero (or any multiple of Math.PI).

    The elegance of this solution, in my opinion, comes from the lack of any "magic" numbers (besides 10000, which represents about the minimum amount of digits you must throw away to avoid odd patterns - see results with values 10, 100, 1000). Brevity is also nice.

    It's a bit slower than Math.random() (by a factor of 2 or 3), but I believe it's about as fast as any other solution written in JavaScript.

    0 讨论(0)
提交回复
热议问题