简体   繁体   English

随机数和地板与圆形功能

[英]Random numbers and floor vs round function

为什么我使用随机数生成器并且范围为0 - 9我没有得到与将其与floor功能相结合的相同均匀分布?

Math.floor(Math.random() * 10) gives quite uniform distribution, while Math.round(Math.random() * 10) doesn't. Math.floor(Math.random() * 10)给出了非常均匀的分布,而Math.round(Math.random() * 10)则没有。

Math.floor() returns 0 for any value in the range [0, 1) (1 exclusive), 1 for any value in the range [1, 2), etc. Math.floor()为范围[0,1)中的任何值(1不包括)返回0,对于范围[1,2]中的任何值返回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. 因此,如果我们在这些范围之一中获得数字的机会相等,我们将得到0和1的平均分布。

Math.round(), however, returns 0 for values under 0.5, 1 for values under 1.5, etc. 但是,Math.round()对于0.5以下的值返回0,对于1.5以下的值返回1等。

So we actually have half the chances of getting a 0, as only values from 0 to 0.5 will round to 0. 所以我们实际上有一半获得0的机会,因为只有从0到0.5的值将舍入为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 ║
╚═════════╩═════════╩═════════╝

I really like to trigger 31-bit int instead of Math.floor() , by doing a binary "or 0" operation. 我真的想通过执行二进制“或0”操作来触发31位int而不是Math.floor() It makes it slightly faster (stack vs heap,) seems a tad neater, and does the same thing, in a practical sense. 它使得它稍微更快(堆栈与堆,)似乎有点整洁,并在实际意义上做同样的事情。 Here is an example that gets a random element of an array: 这是一个获取数组的随机元素的示例:

var ar=[1,2,3,4,5,6,7,8,9,0,'a','b','c','d']
console.log(ar[(Math.random() * ar.length) |0])

This might seem like premature optimization, but as I said, I like how it looks, and it takes less typing than Math.floor() . 这似乎是过早优化,但正如我所说,我喜欢它的外观,并且它比Math.floor()需要更少的输入。 Using Math.round() would require an extra step (because the spread is 1 to ar.length not 0 to ar.length-1 ) 使用Math.round()需要一个额外的步骤(因为扩展为1ar.length而不是0ar.length-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM