比如说获取一个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呢?
比如说获取一个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呢?
如果是取[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$$。你自己看看这概率有多小咯。
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
ceil是向上取整,Math.ceil(Math.random()*10),当只有取到0的时候才是0,所以几率很小
floor是向下取整,Math.ceil(Math.random()*(10+1)),相当于你在0到11间取,取到的数向下取整,可以相对来说取到0-10的整数几率差不多