简体   繁体   中英

A random number generator that can get different numbers in < a second

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?

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.

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.

您只能将PRNG播种一次

Boost.Random具有各种非常好的随机数生成器。

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;

This code generates a unique random number only once.

#include <ctime>
# include <iostream>
using namespace std;


int main()
{

      int size=100;
      int random_once[100];
      srand(time(0));

      for (int i=0;i<size;i++)  // generate unique random number only once
      {
          random_once[i]=rand() % size;
          for(int j=0;j<i;j++) if (random_once[j]==random_once[i]) i--;   
      }

      for ( i=0;i<size;i++) cout<<" "<<random_once[i]<<"\t";

  return 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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