What's the difference between arc4random and arc4random_uniform?

Objective CRandomArc4random

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrennan AdlerView Question on Stackoverflow
Solution 1 - Objective CConnorView Answer on Stackoverflow