A random number generator that can receive different numbers in <second

I need a C ++ random number generator (pseudo, I don't care) that can get different numbers every time I call the function. It might just be the way I seed it, maybe there is a better method, but every random generator I have doesn't generate a new number every time it is called. I sometimes need to get several random numbers per second, and with any RNG plugin I tend to get the same number multiple times in a row. Of course I know why, because it is seeded second, so it only generates a new number every second, but I need to somehow get a new number on every call. Can someone point me in the right direction?

+1


source share


6 answers


It looks like you do it like this:

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

      

Which explains why you get the same number in one second. But you have to do it like this:



int get_rand() {
    return rand();
}

      

And call srand once when the program starts.

+17


source


You only need to split the generator using srand()

at startup, then just call the function rand()

. If you repopulate a generator with the same seed twice, you will get the same value every time.



+7


source


You only need to split the PRNG once .

+4


source


Boost.Random has a lot of good random number generators.

+3


source


If you are generating a lot of random numbers, you can try the XORShift generator. For lengths (8 bits):

// 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;

      

+1


source


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;

      

0


source







All Articles