views:

803

answers:

3

Using

   value = arc4random() % x

How can I avoid or eliminate modulo bias?

Thanks all.

BTW, at least according to Wikipedia, modulo bias is an issue when programming games of chance.

+2  A: 

arc4random returns a 32-bit unsigned integer (0 to 232-1).

There will probably be no noticable modulo bias for small enough x. However, if you want to be really sure, do this:

y = 2p where 2p-1 < x ≤ 2p

val = arc4random() % y;
while(val >= x)
    val = arc4random() % y;
Can Berk Güder
You're welcome. =)
Can Berk Güder
+1  A: 

If the maximum value of arc4random mod x is greater than x, ignore any values larger than the largest arc4random-max mod x, calling arc4random again instead.

Jason Cohen
+2  A: 
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;

although unless you are using any x under a million (or more) I wouldn't worry about it

cobbal