how to generate uncorrelated random sequences usin

2019-07-18 20:52发布

I'd like to generate two sequences of uncorrelated normal distributed random numbers X1, X2.

As normal distributed random numbers come from uniform numbers, all I need is two uncorrelated uniform sequences. But how to do it using:

srand (time(NULL));

I guess I need to seed twice or do something similar?

标签: c++ math random
3条回答
祖国的老花朵
2楼-- · 2019-07-18 21:28

rand doesn't support generating more than a single sequence. It stores its state in a global variable. On some systems (namely POSIX-compliant ones) you can use rand_r to stay close to that approach. You'd simply use some initial seed as internal state for each. But since your question is tagged C++, I suggest you use the random number facilities introduced in C++11. Or, if C++11 is not an option, use the random module from boost.

A while ago I've asked a similar question, Random numbers for multiple threads, the answers to which might be useful for you as well. They discuss various aspects of how to ensure that sequences are not interrelated, or at least not in an obvious way.

查看更多
男人必须洒脱
3楼-- · 2019-07-18 21:32

Since the random numbers generated by a high-quality random-number generator are uniform and independent, you can generate as many independent sequences from it as you like.

You do not need, and should not seed two different generators.

In C++(11), you should use a pseudo-random number generator from the header <random>. Here’s a minimal example that can serve as a template for an actual implementation:

std::random_device seed;
std::mt19937 gen{seed()};

std::normal_distribution<> dist1{mean1, sd1};
std::normal_distribution<> dist2{mean2, sd2};

Now you can generate independent sequences of numbers by calling dist1(gen) and dist2(gen). The random_device is used to seed the actual generator, which in my code is a Mersenne Twister generator. This type of generator is efficient and has good statistical properties. It should be considered the default choice for a (non cryptographically secure) generator.

查看更多
贼婆χ
4楼-- · 2019-07-18 21:45

Use two random_devices (possibly with some use of engine) with a normal_distribution from <random> :

std::random_device rd1, rd2;
std::normal_distribution d;
double v1 = d(rd1);
double v2 = d(rd2);
...

See also example code at http://en.cppreference.com/w/cpp/numeric/random/normal_distribution

查看更多
登录 后发表回答