52

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?

Lucas
  • 523
  • 2
  • 10
  • 20
Brennan Adler
  • 895
  • 2
  • 8
  • 18
  • It means what the readily-available documentation says it means. Did you have a specific question about the documentation? – Hot Licks Apr 29 '15 at 22:52
  • 1
    The difference between these two functions in Swift is exactly the same as the difference between these two functions in (Objective-)C(++). They're the same functions, with the same behavior, no matter what language you call them from. – rickster Apr 29 '15 at 23:00

1 Answers1

111

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.

Steven Fisher
  • 44,462
  • 20
  • 138
  • 192
Connor Pearson
  • 63,902
  • 28
  • 145
  • 142
  • 1
    Is it between 0 and 5, i.e., 0, 1, 2, 3, 4, 5 are possible values, or is it 0, 1, 2, 3, 4? From documentation, it says "less than" upper bound and not "less than or equal to" upper bound. – Van Du Tran Nov 12 '15 at 18:27
  • 3
    @VanDuTran it is not inclusive of the upper bounds. So {0, 1, 2, 3, 4} in your example. – JaredH Jan 22 '16 at 18:10