简体   繁体   English

生成两个独立的随机数序列(C ++)

[英]Generating two independent random number sequences (C++)

I'd like to be able to do something like this (obviously not valid C++): 我希望能够做这样的事情(显然不是有效的C ++):

rng1 = srand(x)
rng2 = srand(y)

//rng1 and rng2 give me two separate sequences of random numbers
//based on the srand seed
rng1.rand()
rng2.rand()

Is there any way to do something like this in C++? 有没有办法在C ++中做这样的事情? For example in Java I can create two java.util.Random objects with the seeds I want. 例如在Java中,我可以使用我想要的种子创建两个java.util.Random对象。 It seems there is only a single global random number generator in C++. 似乎C ++中只有一个全局随机数生成器。 I'm sure there are libraries that provide this functionality, but anyway to do it with just C++? 我确信有些库提供了这种功能,但无论如何只用C ++来实现它?

使用rand_r

In TR1 (and C++0x), you could use the tr1/random header. 在TR1(和C ++ 0x)中,您可以使用tr1/random标头。 It should be built-in for modern C++ compilers (at least for g++ and MSVC ). 它应该内置于现代C ++编译器(至少对于g ++MSVC )。

#include <tr1/random>
// use #include <random> on MSVC
#include <iostream>

int main() {

    std::tr1::mt19937 m1 (1234);  // <-- seed x
    std::tr1::mt19937 m2 (5678);  // <-- seed y

    std::tr1::uniform_int<int> distr(0, 100);

    for (int i = 0; i < 20; ++ i) {
        std::cout << distr(m1) << "," << distr(m2) << std::endl;
    }

    return 0;
}

You could also use Boost.Random . 你也可以使用Boost.Random

More technical documentation here. 这里有更多技术文档

I just want to point out, that using different seeds may not give you statistically independent random sequences. 我只是想指出,使用不同的种子可能不会给你统计独立的随机序列。 mt19937 is an exception. mt19937是个例外。 Two mt19937 objects initialized with different seeds will give you more or less (depending whom you ask) statistically independent sequences with very high probability (there is a small chance that the sequences will overlap). 用不同的种子初始化的两个mt19937对象将给你或多或少(取决于你所要求的)具有非常高概率的统计独立序列(序列重叠的可能性很小)。 Java's standard RNG is notoriously bad. Java的标准RNG非常糟糕。 There are plenty of implementations of mt19937 for Java, which should be preferred over the stock RNG. 有很多用于Java的mt19937实现,它应该比库存RNG更受欢迎。

For whatever reason, the following generators interfere with each other. 无论出于何种原因,以下发生器互相干扰。 I need two independent generators for a task and need to reconstruct the streams. 我需要两个独立的生成器来完成任务,需要重建流。 I haven't dug into the code but the std::tr1 and C++11 generators seem to share states in common. 我没有挖掘代码,但std :: tr1和C ++ 11生成器似乎共享状态。 Adding m2 below changes what m1 will deliver. 添加m2会改变m1将提供的内容。

std::tr1::mt19937 m1 (1234);  // <-- seed x
std::tr1::mt19937 m2 (5678);  // <-- seed y

I had to build my own to ensure independence. 我必须建立自己的以确保独立性。

as @James McNellis said, I can't imagine why do you would do that, and what pros you will get. 正如@James McNellis所说,我无法想象你为什么会这样做,以及你会得到什么样的专业人士。 Describe what effect you would like to achieve. 描述您想要达到的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM