javascript 你如何获得准确的 50% 几率?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21507133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you get exactly 50% odds?
提问by IQAndreas
Which of these will give an exactly50% chance when a random value is a float between 0 and 1 (such as AS3's or JavaScript's Math.random()
)? I have seen both of them used in practice:
当随机值是介于 0 和 1 之间的浮点数(例如 AS3 或 JavaScript 的)时,以下哪一项将给出恰好50% 的机会Math.random()
?我已经看到它们都在实践中使用过:
if (Math.random() > 0.5) ...
if (Math.random() >= 0.5) ...
Heads up:I'm being pedantic here, because in practice, hitting exactly 0.5
is astronomically low. However, I would still like to know where is the middle of 0 inclusive
and 1 exclusive
.
注意:我在这里很迂腐,因为在实践中,准确命中率0.5
是天文数字。但是,我仍然想知道0 inclusive
and的中间在哪里1 exclusive
。
回答by abiessu
Mathematically speaking, a test which is intended to split the interval [0,1)
(using [
as "inclusive" and )
as exclusive) in an exact 50-50 ratio would use a comparison like
从数学上讲,旨在以精确的 50-50 比率分割区间[0,1)
([
用作“包含”和)
“排除”)的测试将使用类似的比较
if (Math.random() >= 0.5) ...
This is because this splits the initial interval [0,1)
into two equal intervals [0,0.5)
and [0.5,1)
.
这是因为这将初始间隔[0,1)
分成两个相等的间隔[0,0.5)
和[0.5,1)
。
By comparison, the test
相比之下,测试
if (Math.random() > 0.5) ...
splits the interval into [0,0.5]
and (0.5,1)
, which have the same length, but the first is boundary-inclusive while the second is not.
将区间拆分为[0,0.5]
和(0.5,1)
,它们具有相同的长度,但第一个是包含边界的,而第二个不是。
Whether the boundaries are included in the same way in both tests does not matter in the limit as the precision approaches infinite, but for all finite precision, it makes a minute but measurable difference.
在两个测试中边界是否以相同的方式包含在限制中并不重要,因为精度接近无限,但对于所有有限精度,它会产生微小但可测量的差异。
Suppose the precision limit is 0.000001
(decimal), then the >=0.5
test has exactly [0,0.499999]
and [0.5,0.999999]
and it is plain to see that adding 0.5 to the first interval (or subtracting it from the second) makes the two intervals align perfectly. On the other hand, under this precision, the >0.5
test makes the intervals [0,0.5]
and [0.500001,0.999999]
which are clearly unequal in favor of the numbers <=0.5
. In fact, the ratio is then 500001:499999, which is obviously negligibly different from 50:50, but different all the same.
假设精度限制是0.000001
(十进制),那么>=0.5
测试正好有[0,0.499999]
并且[0.5,0.999999]
很明显,将 0.5 添加到第一个间隔(或从第二个间隔中减去)使两个间隔完美对齐。另一方面,在这种精度下,>0.5
测试使间隔[0,0.5]
和[0.500001,0.999999]
明显不等,有利于数字<=0.5
。事实上,那么这个比例就是500001:499999,这与50:50的差别显然可以忽略不计,但都一样。