什么是arc4random和arc4random_uniform之间的区别? [英] What's the difference between arc4random and arc4random_uniform?

查看:324
本文介绍了什么是arc4random和arc4random_uniform之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我已经看到了有关的OBJ随机arc4random之间的差异旧文章。 C,我已经看到了答案,这个在线,但我真的不知道答案,所以我希望这里有人可以在一个解释更容易理解的方式。

So I've seen old posts about the difference between random and arc4random in Obj. C, and I've seen answers to this online but I didn't really understand the answers so I was hoping someone here could explain it in an easier to understand manner.

什么是两者的区别: arc4random arc4random_uniform 来产生随机数?

What is the difference between using arc4random and arc4random_uniform to generate random numbers?

推荐答案

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

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.

男子3 arc4random

arc4random_uniform()将返回比UPPER_BOUND以下的均匀分布的随机数。 arc4random_uniform()建议在像``arc4random()%UPPER_BOUND'结构,因为它避免了模数偏见的时候,上限是不是2的力量。

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.

例如,如果你想要一个整数,你可以使用4个介于0和

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

arc4random() % 5

arc4random_uniform(5)

在这种情况下,使用模运算引入模偏见,所以最好使用arc4random_uniform。

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

要了解模偏置假设 arc4random 有一个更小的范围内。而不是0到(2 ^ 32)-1,它是0至(2 ^ 4)-1。如果在该范围内的每个数字执行%5,你会得到0四次,1,2,3和4 3次,每次使0更可能发生。这种差异变得时的范围大得多少显著,但它仍然是最好避免使用模量。

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.

这篇关于什么是arc4random和arc4random_uniform之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆