arc4random 随机数生成器
int randomNumber = (arc4random() % 83) + 1;
这是生成“最随机”数字的最佳方法吗?或者有更好的方法来生成随机数吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您使用 arc4random 时,您可以避免将
%
与线性同余生成器(这是rand
使用的常用算法)一起使用的一个陷阱:顺序位的随机性并不低。但是,您仍然遇到截断问题:即,因为
(1 << 32) % 83
是 77,这意味着 0 到 76 之间的数字比 77 到 77 之间的数字出现(稍微)更频繁。 82. 为了避免这种情况,如果传入值高于(1 << 32) / 83 * 83
,则应丢弃它(即再次调用arc4random
)。(我假设 arc4random 的范围是从 0 到 232-1。相应地调整上面的解释。)
When you use
arc4random
you avoid one pitfall of using%
with linear congruential generators (which is the usual algorithm used byrand
): the low-order bits aren't less random.However, you still have truncation issues: i.e., because
(1 << 32) % 83
is 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., callarc4random
again) if it's above(1 << 32) / 83 * 83
.(I assume the range of
arc4random
is from 0 to 232-1. Adjust the above explanation accordingly.)arc4random 具有基于当前时间生成随机数的高级算法。还有其他 rand 函数,但它们不太好并且需要播种。
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.
我见过的最好的随机数生成器(以及随机含义的非常清晰的定义)可以在 Stephen Wolfram 的《一种新科学》中找到。几十年来,他一直在 Mathematica 软件程序中使用一个非常简单的元胞自动机作为随机数生成器,因此它经过了非常好的测试。
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.