I am using arc4random() %2
in my code. It is called by 3 classes upon initialization, which happens in quick succession. However, approximately 70% plus of the results are always either all 0 or all 1 (the distribution between the 2 sets of 000 or 111 seems average). I would have expected a fairly random distribution of 1 and 0 between the 3 classes. How can this be explained?
Asked
Active
Viewed 309 times
4

RunLoop
- 20,288
- 21
- 96
- 151
-
1Could this be a seeding issue? – RunLoop Aug 17 '13 at 17:03
-
Are you creating one arc4random(), or multiple instances? If multiple, are you seeding them independently? – pjs Aug 17 '13 at 17:07
-
2@pjs it is not possible to directly seed arc4random – RunLoop Aug 17 '13 at 17:16
-
Do you have some code that demonstrates this? – jscs Aug 17 '13 at 19:14
-
1Please post some code. – uchuugaka Aug 19 '13 at 10:01
2 Answers
1
Although I cannot say this definitively, it does appear to be a seeding "issue". Calling arc4random() multiple times within milliseconds of each other will have a very high bias towards certain numbers. acr4random_uniform seems to solve this problem - seemingly it is seeded in a more "robust" manner

RunLoop
- 20,288
- 21
- 96
- 151
-1
Use acr4random_unform(3)
to avoid modulo bias
Read This Article:- http://nshipster.com/random/

Burhanuddin Sunelwala
- 5,318
- 3
- 25
- 51
-
As was noted under the other answer which made the same suggestion _two days ago_, this isn't a case of modulo bias. – jscs Aug 20 '13 at 08:25