Seeding the random number generator in Javascript

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

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

13条回答
  •  庸人自扰
    2020-11-22 10:12

    Antti Sykäri's algorithm is nice and short. I initially made a variation that replaced JavaScript's Math.random when you call Math.seed(s), but then Jason commented that returning the function would be better:

    Math.seed = function(s) {
        return function() {
            s = Math.sin(s) * 10000; return s - Math.floor(s);
        };
    };
    
    // usage:
    var random1 = Math.seed(42);
    var random2 = Math.seed(random1());
    Math.random = Math.seed(random2());
    

    This gives you another functionality that JavaScript doesn't have: multiple independent random generators. That is especially important if you want to have multiple repeatable simulations running at the same time.

提交回复
热议问题