c++ - 初始化 srand 的推荐方法?

标签 c++ random srand

我需要一种“好的”方法来初始化 C++ 中的伪随机数生成器。我找到了an article说明:

In order to generate random-like numbers, srand is usually initialized to some distinctive value, like those related with the execution time. For example, the value returned by the function time (declared in header ctime) is different each second, which is distinctive enough for most randoming needs.

Unixtime 对我的应用程序来说不够独特。初始化它的更好方法是什么?如果它是可移植的,则加分,但代码将主要在 Linux 主机上运行。

我正在考虑做一些 pid/unixtime 数学来获得一个 int,或者可能从 /dev/urandom 读取数据。

谢谢!

编辑

是的,我实际上是在每秒多次启动我的应用程序并且遇到了冲突。

最佳答案

这是我用于可以频繁运行的小型命令行程序(每秒多次):

unsigned long seed = mix(clock(), time(NULL), getpid());

混合在哪里:

// Robert Jenkins' 96 bit Mix Function
unsigned long mix(unsigned long a, unsigned long b, unsigned long c)
{
    a=a-b;  a=a-c;  a=a^(c >> 13);
    b=b-c;  b=b-a;  b=b^(a << 8);
    c=c-a;  c=c-b;  c=c^(b >> 13);
    a=a-b;  a=a-c;  a=a^(c >> 12);
    b=b-c;  b=b-a;  b=b^(a << 16);
    c=c-a;  c=c-b;  c=c^(b >> 5);
    a=a-b;  a=a-c;  a=a^(c >> 3);
    b=b-c;  b=b-a;  b=b^(a << 10);
    c=c-a;  c=c-b;  c=c^(b >> 15);
    return c;
}

关于c++ - 初始化 srand 的推荐方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/322938/

相关文章:

c++ - std::random_shuffle 产生相同的结果,即使 srand(time(0)) 被调用一次

c++ - openMP 使用相同的种子生成不同的随机数

c++ - "Is there a better way?"Windows Vista 上的 wininet 错误 12029

c++ - 如何在 C++ 中将 localtime_s 与指针一起使用

c++ - 一个多索引,其中一个索引是整个集合的一个子集

c++ - 派生类不调用整个基础构造函数

python - 从文本文件中随机选择句子,找到对应的ID号

java.util.UUID.randomUUID().toString() 长度

c# - asp.net/c# 中的随机函数有多安全

c++ - 相同的随机数