objective-c arc4random 和 arc4random_uniform 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29955823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:34:15  来源:igfitidea点击:

What's the difference between arc4random and arc4random_uniform?

objective-crandomarc4random

提问by Brennan Adler

I've seen old posts about the differences between randomand arc4randomin 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.

我看过关于Objective-Crandomarc4randomObjective-C之间差异的旧帖子,我在网上看到了这个答案,但我不太明白,所以我希望这里有人能以更容易理解的方式解释它.

What is the difference between using arc4randomand arc4random_uniformto generate random numbers?

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

回答by Connor

arc4randomreturns an integer between 0 and (2^32)-1 while arc4random_uniformreturns an integer between 0 and the upper bound you pass it.

arc4random返回 0 到 (2^32)-1arc4random_uniform之间的整数,同时返回 0 和传递给它的上限之间的整数。

From man 3 arc4random:

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

arc4random_uniform() 将返回一个小于 upper_bound 的均匀分布的随机数。arc4random_uniform() 被推荐用于类似 ``arc4random() % upper_bound'' 的结构,因为当上限不是 2 的幂时,它可以避免“模偏差”。

For example if you want an integer between 0 and 4 you could use

例如,如果你想要一个 0 到 4 之间的整数,你可以使用

arc4random() % 5

or

或者

arc4random_uniform(5)

Using the modulus operator in this case introduces modulo bias, so it's better to use arc4random_uniform.

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

To understand modulo bias assume that arc4randomhad 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.

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