64 位随机种子 [英] Seed random in 64-Bit

查看:36
本文介绍了64 位随机种子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过 iPhone 5S 更新,我希望我的应用能够支持新的 64 位处理器.

With the iPhone 5S update I want my app to be able to support the new 64-Bit processor.

但是,如果将较大的数据类型转换为较小的数据类型(例如将 long 转换为 int),则使用 64 位可能会导致截断.大多数情况下,这可以通过使用更大的数据类型轻松解决,但对于有时使用time(NULL)"函数播种的随机数生成器,我无法做到这一点.

However, using 64-Bit may cause truncation if a larger data type is casted into a smaller one, as in the case of casting a long into an int. Most of the time this can be easily fixed by just using the bigger data type, but in the case of random number generators which are sometimes seeded by using the "time(NULL)" function I cannot do that.

当前代码很简单:

srandom(time(NULL));

但在 64 位的 XCode 5 中,它会导致以下错误:隐式转换失去整数精度:'time_t'(又名'long')到'unsigned int'.这是因为time(NULL)"返回一个长整数而srandom"需要一个无符号整数.因此有两种选择:

But in XCode 5 with 64-Bit it is causing the following error: Implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int'. This is because "time(NULL)" returns a long integer and "srandom" requires an unsigned int. Therefore there are two options:

  1. 将长整数转换为无符号整数
  2. 用另一个执行相同工作但返回无符号整数的函数替换time(NULL)".

你会推荐哪一个,我应该使用什么函数来做到这一点?

Which one would you recommend and what function should I use to do it?

注意:我使用 random() 而不是 arc4random() 因为我还需要能够为随机数生成器设置种子以获得可重复的结果.

NOTE: I use random() instead of arc4random() because I also need to be able to seed the random number generator in order to get a repeatable outcome.

推荐答案

time() 通常返回自纪元以来的秒数(不计算闰秒),这意味着如果你使用它更多超过一秒钟(或两个人同时运行该程序)然后它将返回相同的值,即使您不想要它也会导致重复的序列.我建议不要使用 time(NULL) 作为种子,即使没有由截断引起的警告(或 -Werror 错误).

time() typically returns the number of seconds since the epoch (not counting leap seconds), which means if you use it more than once in a second (or two people run the program at the same time) then it will return the same value, resulting in a repeated sequence even when you don't want it. I recommend against using time(NULL) as a seed, even in the absence of a warning (or error with -Werror) caused by the truncation.

您可以使用 arc4random() 来获取随机种子而不是基于时间的种子.它也碰巧返回一个无符号的 32 位值,这将修复您看到的错误.

You could use arc4random() to get a random seed instead of a seed based on time. It also happens to return an unsigned 32-bit value which will fix the error you're seeing.

srandom(arc4random());

<小时>

您可能会考虑迁移到 Objective-C++,以便您可以使用标准的 C++ <random> 库,该库更加强大和灵活,并且还可以更简单、更直接地表达许多想法,比这些其他图书馆


You might consider moving to Objective-C++ so that you can use the standard C++ <random> library, which is much more powerful and flexible, and which also enables simpler and more direct expression of many ideas, than these other libraries

C++ 文档

这篇关于64 位随机种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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