js获取随机数的问题

比如说获取一个0~10的随机数,可以想到下面两种

Math.ceil(Math.random()*10);
Math.floor(Math.random()*(10+1));

但是看到有人说用Math.ceil(Math.random()*10);时取0的几率极小。
用Math.floor(Math.random()*(10+1));时,可均衡获取0到10的随机整数。
真的是这样吗?那是不是以后获取随机数用floor不用ceil呢?

阅读 3k
4 个回答

ceil是向上取整,Math.ceil(Math.random()*10),当只有取到0的时候才是0,所以几率很小
floor是向下取整,Math.ceil(Math.random()*(10+1)),相当于你在0到11间取,取到的数向下取整,可以相对来说取到0-10的整数几率差不多

如果是取[0,10]的整数,标准的方法就是Math.floor(Math.random()*(10+1))
如果是取[0,10)的整数,标准的方法是Math.floor(Math.random()*10)
用ceil无论怎么处理都有问题的。

如果是取(0,10]的整数,标准的方法就是Math.ceil(Math.random()*10),这时用floor怎么都会有问题的。

这是一个数学问题。首先你要明白Math.ceil是向上取整,也就是说,像0.000000000000000000001这样这么小数向上取整完了也会是1;然后是取值范围的问题,$$Math.random() \in [0, 1)$$,向上取整后$$Math.ceil(Math.random()) \in [0, 1]$$,此时,$$Math.ceil(Math.random()) = 0$$的充要条件即$$Math.random() = 0.0$$。假设Math.random()是理想的随机数生成器(精确到小数点后无穷大位),则$$P(Math.random() = 0.0) = 0$$,若Math.random()精确到二进制小数点后n位,则$$P(Math.random() = 0.0) = 1 / 2^n$$。你自己看看这概率有多小咯。

楼上已经将区别很好地解释了 还有一种方法可以试试 ~~(0 + Math.random() * 10)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题