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.其他的范围是类似的,就不说了。感兴趣的可以多练练
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值