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

查看:69
本文介绍了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中,它导致以下错误:Implicit conversion loses integer precision: 'time_t' (aka 'long') to 'unsigned int'.这是因为"time(NULL)"返回一个长整数,而"srandom"则需要一个无符号的int.因此,有两种选择:

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()通常返回自纪元以来的秒数(不计算seconds秒),这意味着如果您每秒使用一次以上(或两个人同时运行该程序),那么它将返回相同的值,即使您不想要它也将导致重复的序列.我建议不要使用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 ++ <random>文档

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

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