Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

c++ - Using boost::random and getting same sequence of numbers

I have the following code:

Class B {

void generator()
{
    // creating random number generator
    boost::mt19937 randgen(static_cast<unsigned int>(std::time(0)));
    boost::normal_distribution<float> noise(0,1);
    boost::variate_generator<boost::mt19937, 
        boost::normal_distribution<float> > nD(randgen, noise);


    for (int i = 0; i < 100; i++)
    {
        value = nD();
        // graph each value
    }
}
};

Class A {

void someFunction()
{
    for(int i = 1; i <=3; i++)
    {
        std::shared_ptr<B> b;
        b.reset(new B());
        b->generator();
    }
}
};

I wish to execute the above code multiple times in rapid succession to produce multiple graphs. I have also reviewed this stackoverflow question which is similar but the caveat states that when time(0) is used and the member function is called in rapid succession then you will still likely get the same sequence of numbers.

How might I overcome this problem?

EDIT: I've tried making randgen static in Class B, also tried making it a global variable in Class A, but each time the 3 graphs are still the same. I've also tried seeding from the GetSystemTime milliseconds. I must be missing something.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way would be to not reseed the random number generator every time you execute your code.

Create the generator and seed it once, then just continue to use it.

That's assuming you're calling that code multiple times within the same run. If you're doing multiple runs (but still within the same second), you can use another differing property such as the process ID to change the seed.

Alternatively, you can go platform-dependent, using either the Windows GetSystemTime() returning a SYSTEMTIME structure with one of its elements being milliseconds, or the Linux getTimeOfDay returning number of microseconds since the epoch.

Windows:

#include <windows.h>
SYSTEMTIME st;
GetSystemTime (&st);
// Use st.wSecond * 100 + st.wMillisecs to seed (0 thru 59999).

Linux:

#include <sys/time.h>
struct timeval tv;
gettimeofday (&tv, NULL);
// Use tv.tv_sec * 100 + (tv.tv_usec / 1000) to seed (0 thru 59999).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...