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

血红的双手。 提交于 2019-11-27 20:22:43
Connor

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!