Random Numbers in Objective-C Using Mod Range?
I have read here -- without understanding much -- that it's bad to use mod range. So this typical recommendation for Objective-C
int r = arc4r开发者_JAVA技巧andom() % 45;
might be a bad idea to get a number from 0 to 45 (something about the distribution and this formula having a preference for low bits). What should one use in Objective-C?
<sarcasm> I am so glad to be able to finally learn this stuff after using only high-level languages (Java et. al) all this time. Tomorrow I will try to make fire with two twigs. </sarcasm>
Java is just as high level as Objecive C here - in this case Java' Random.getInt() is the same as arc4random in that they both return a 32-bit pseudo-random number.
The issue raised in the URL (and I have seen elsewhere) is that rand()
could be repeating itself every 32768 values.
Whilst OSX's arc4random could have (2**1700) states.
But as in all uses of pseudo-random generators you need to be aware of their weaknesses before using them e.g. a preference for low bits in some generators and also the comment in the OpenBSD arc4random man page where it says
arc4random_uniform() is recommended over constructions like ``arc4random() % upper_bound'' as it avoids "modulo bias" when the upper bound is not a power of two.
精彩评论