Search code examples
objective-crandomarc4random

What's the difference between arc4random and arc4random_uniform?


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?


Solution

  • 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.