I've seen old posts about the differences between random
and arc4random
in Objective-C, and I've seen answers to this online but I didn't really understand, so I was hoping someone here could explain it in an easier-to-understand manner.
What is the difference between using arc4random
and arc4random_uniform
to generate random numbers?
arc4random_uniform(n) returns a random number between zero and the (parameter minus one). drand48() returns a random Double between 0.0 and 1.0. Note: Both arc4random() and arc4random_uniform() use the type UInt32 instead of the more typical Int. Thus, there is a need for conversion for ease of use.
How Do I Generate a Random Number in Objective-C? tl;dr: Use arc4random() and its related functions. Specifically, to generate a random number between 0 and N - 1 , use arc4random_uniform() , which avoids modulo bias.
arc4random
returns an integer between 0 and (2^32)-1 while arc4random_uniform
returns an integer between 0 and the upper bound you pass it.
From man 3 arc4random
:
arc4random_uniform() will return a uniformly distributed random number less than upper_bound. 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.
For example if you want an integer between 0 and 4 you could use
arc4random() % 5
or
arc4random_uniform(5)
Using the modulus operator in this case introduces modulo bias, so it's better to use arc4random_uniform.
To understand modulo bias assume that arc4random
had a much smaller range. Instead of 0 to (2^32) -1, it was 0 to (2^4) -1. If you perform % 5 on each number in that range you will get 0 four times, and 1, 2, 3 and 4 three times each making 0 more likely to occur. This difference becomes less significant when the range is much larger, but it's still better to avoid using modulus.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With