Math.random() 生成指定范围随机整数的思考

Math.random()    生成的是[0, 1)之间的伪随机数。注意左闭右开

1.第一种范围,也是最常用的用法,[min, max],均是闭区间。

为了方便我们举两个数, [2, 8]之间

0____1_____2_____3____4____5____6___7____8_____9____10

1)如果我们使用Math.floor来近似的话,可以像这样看,就以2为例,

2到3区间的数都属于2,例如2.0001, 2.67,2.9999。如果以8为例的话

8.1,8.999也都属于8。因此我们可以推出, 

 Math.floor(Math.random() * (8 - 2 + 1) + 2);

由于是向下取整,我们的步长应该需要加1,才可以取到8到9之间的数,不包含9

通用:

Math.floor(Math.random() * (max - min + 1) + min)

下面我们写个测试函数来简单验证一下,是否符合平均分布

function random(cnt) {
    /*
        @cnt: [Number],需要测试的次数
    */
    var random;
    var result = {};
    for(var i=0; i<cnt; ++i) {
        random = Math.floor(Math.random() * (8 - 2 + 1) + 2);
        if(random in result) {
            result[random]++;
        } else {
            result[random] = 1;
        }
    }
    console.log(result);
    return result;
}

random(100000);

测试结果: 

{2: 14395, 3: 13985, 4: 14519, 5: 14425, 6: 14248, 7: 14162, 8: 14266}

很明显是符合平均分布的。

2)Math.ceil()来模拟,

Math.ceil(Math.random() * (max - min + 1) + min - 1)

3)Math.round来模拟,

Math.round(Math.random() * (max - min + 1) + min - 0.5)
2.其他的范围是类似的,就不说了。感兴趣的可以多练练

猜你喜欢

转载自blog.csdn.net/qq_21058391/article/details/79778866