Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between arc4random and arc4random_uniform? [duplicate]

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?

like image 236
Brennan Adler Avatar asked Apr 29 '15 22:04

Brennan Adler


People also ask

What is arc4random_uniform?

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 you generate a random number in Objective C?

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.


1 Answers

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.

like image 165
Connor Avatar answered Oct 17 '22 22:10

Connor