使用:
value = arc4random() % x如何避免或消除模偏差?
至少根据维基百科的说法,在编写机会游戏时,模偏差是一个问题。
发布于 2011-06-01 06:08:12
使用arc4random_uniform(x)。这就为你做了。
根据手册页:
arc4random_uniform()将返回一个小于upper_bound的均匀分布的随机数。推荐使用arc4random_uniform()而不是像arc4random() % upper_bound这样的构造,因为当上限不是2的幂时,它可以避免“模偏差”。
发布于 2009-03-15 23:24:07
u_int32_t maxValue = ~((u_int32_t) 0); // equal to 0xffff...
maxValue -= maxValue % x; // make maxValue a multiple of x
while((value = arc4random()) >= maxValue) { // loop until we get 0 ≤ value < maxValue
}
value %= x;不过,除非您使用的x小于一百万(或更多),否则我不会担心
发布于 2009-03-15 22:57:24
如果arc4random mod x的最大值大于x,则忽略任何大于最大arc4random-max mod x的值,重新调用arc4random。
https://stackoverflow.com/questions/648739
复制相似问题