xcode arc4random 随机数生成器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4435905/
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-14 20:00:45  来源:igfitidea点击:

arc4random Random Number Generator

iphoneobjective-cxcoderandomarc4random

提问by Linuxmint

int randomNumber = (arc4random() % 83) + 1;

Is this the best way to generate "the most random" number? Or is there a better way to generate a random number?

这是生成“最随机”数字的最佳方式吗?或者有没有更好的方法来生成随机数?

回答by Chris Jester-Young

When you use arc4randomyou avoid one pitfall of using %with linear congruential generators (which is the usual algorithm used by rand): the low-order bits aren't less random.

当您使用时,arc4random您可以避免使用%线性同余生成器(这是 使用的常用算法rand)的一个陷阱:低阶位不那么随机。

However, you still have truncation issues: i.e., because (1 << 32) % 83is 77, that means that numbers between 0 and 76 appear (slightly) more frequently than numbers between 77 and 82. To avoid this, you should throw away the incoming value (i.e., call arc4randomagain) if it's above (1 << 32) / 83 * 83.

但是,您仍然存在截断问题:即,因为(1 << 32) % 83是 77,这意味着 0 到 76 之间的数字比 77 和 82 之间的数字出现(稍微)更频繁。为避免这种情况,您应该丢弃传入的值(即调用arc4random再次)如果它在(1 << 32) / 83 * 83.

(I assume the range of arc4randomis from 0 to 232-1. Adjust the above explanation accordingly.)

(我假设范围arc4random是从 0 到 2 32-1。相应地调整上面的解释。)

回答by prgmast3r

arc4random has a superior algorithm for generating random numbers based on the current time. There are other rand functions but they are not as good and require seeding.

arc4random 具有基于当前时间生成随机数的高级算法。还有其他 rand 函数,但它们没有那么好并且需要播种。

回答by Brian Shriver

The best random number generator I've ever seen (as well as a very clear definition of what random means) can be found in Stephen Wolfram's A New Kind of Science. He's been using a very simple cellular automata as his random number generator for decades in his Mathematica software program so it's been extremely well tested.

我见过的最好的随机数生成器(以及对随机意味着什么的非常清晰的定义)可以在 Stephen Wolfram 的 A New Kind of Science 中找到。几十年来,他一直在他的 Mathematica 软件程序中使用一个非常简单的元胞自动机作为他的随机数生成器,因此它已经过非常好的测试。