arc4random 和 arc4random_uniform 有什么区别?

What's the difference between arc4random and arc4random_uniform?

我在Objective-C看到过关于randomarc4random的区别的旧帖子,我在网上看到过这个问题的答案,但我不是很明白,所以我希望这里有人能用更容易理解的方式解释它。

使用arc4randomarc4random_uniform生成随机数有什么区别?

arc4random returns 0 和 (2^32)-1 之间的整数,而 arc4random_uniform returns 0 和您传递的上限之间的整数。

来自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.

例如,如果您想要一个介于 0 和 4 之间的整数,您可以使用

arc4random() % 5

arc4random_uniform(5)

在这种情况下使用模运算符会引入模偏差,因此最好使用arc4random_uniform。

要理解模偏差,假设 arc4random 的范围要小得多。它不是 0 到 (2^32) -1,而是 0 到 (2^4) -1。如果您对该范围内的每个数字执行 % 5,您将得到四次 0,以及 1、2、3 和 4 三次,每次都使 0 更有可能出现。当范围更大时,这种差异变得不那么明显,但最好避免使用模数。