随机数和地板与圆形功能 [英] Random numbers and floor vs round function
问题描述
为什么我使用随机数生成器并且范围为0 - 9我没有得到与将它与floor函数相结合的均匀分布?
Why if I use random number generator and range 0 - 9 I don't get the same uniform distribution as combined it with the floor function?
推荐答案
Math.floor(Math.random()* 10)
给出了非常均匀的分布,而 Math.round(Math。 random()* 10)
没有。
Math.floor(Math.random() * 10)
gives quite uniform distribution, while Math.round(Math.random() * 10)
doesn't.
Math.floor()为[0,1]范围内的任何值返回0 (1独家),1表示[1,2]等范围内的任何值。
Math.floor() returns 0 for any value in the range [0, 1) (1 exclusive), 1 for any value in the range [1, 2), etc.
因此,如果我们有相同的机会获得这些范围之一的数字,我们将获得0和1的平均分布。
So if we have equal chances of getting a number in one of these ranges, we will get an equal distribution of 0's and 1's.
Math.round()然而,对于低于0.5的值,返回0,对于低于1.5的值,返回1,等等。
Math.round(), however, returns 0 for values under 0.5, 1 for values under 1.5, etc.
所以我们实际获得0的几率是一半,因为只有从0到0.5的值将舍入为0.
So we actually have half the chances of getting a 0, as only values from 0 to 0.5 will round to 0.
╔═════════╦═════════╦═════════╗
║ Range ║ floor() ║ round() ║
╠═════════╬═════════╬═════════╣
║ [0, 1) ║ 0 ║ 0 or 1 ║
║ [1, 2) ║ 1 ║ 1 or 2 ║
║ [2, 3) ║ 2 ║ 2 or 3 ║
║ ... ║ ... ║ ... ║
║ [9, 10) ║ 9 ║ 9 or 10 ║
╚═════════╩═════════╩═════════╝
这篇关于随机数和地板与圆形功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!