views:

1069

answers:

5

I'm in need of a C++ (pseudo, i don't care) random number generator that can get me different numbers every time I call the function. This could be simply the way I seed it, maybe there's a better method, but every random generator I've got doesn't generate a new number every time it's called. I've got a need to get several random numbers per second on occasion, and any RNG i plug in tends to get the same number several times in a row. Of course, I know why, because it's seeded by the second, so it only generates a new number every second, but I need to, somehow, get a new number on every call. Can anyone point me in the right direction?

+7  A: 

You only need to seed the generator once with srand() when you start, after that just call the rand() function. If you seed the generator twice with the same seed, you'll get the same value back each time.

Eclipse
+14  A: 

Sounds like you do it like this:

int get_rand() {
    srand(time(0));
    return rand();
}

Which would explain why you get the same number within one second. But you have to do it like this:

int get_rand() {
    return rand();
}

And call srand once at program startup.

Johannes Schaub - litb
litb, what would I do without you! Thanks a lot, I had a feeling it was another 'shouldda known better' programmer-inflicted error!
Cyprus106
+4  A: 

You should only seed the PRNG once.

+1  A: 

If you're generating a large number of random numbers, you could try an XORShift generator. For longs (8 bit):

// initial setup
unsigned long x = ... init from time etc ...
// each time we want a random number in 'x':
x ^= x << 21;
x ^= x >> 35;
x ^= x << 4;
Neil Coffey
+3  A: 

Boost.Random has a variety of pretty good random number generators.

Vadim Ferderer