如何JS Math.random方法取得真在平均概率

来源:互联网 发布:c语言初学者百题大战 编辑:程序博客网 时间:2024/06/08 01:01

JS Math.random方法

由于Math.random取得的范围是[0,1),取不到1,如果要想用js做随机数取整,可以使用到如下的公式

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

例如,要取得2-8的随机整数,相当于Math.floor(Math.random()*7+2) 即Math.floor([2,8))

网上有很多用round的方法,实际上是不太准确的,例如Math.round(Math.random()*(max-min)+min),
如果我要取得2-8的整数,相当于Math.floor([2,8)),取得2的只有[2,2,49999999…]这个部分,取得8的只有[7.50000001…,7.99999]这个部分,所以2和8的几率比其他数字少一半

0 0