C ++ random integers

I am trying to generate random integers (evenly spaced). I found this snippet on another forum, but it works in a very strange way.

 srand(time(NULL));
    AB=rand() % 10+1;

      

Using this method, I get the values ​​in a loop, so the value increases with each call until it goes down again. I guess this is due to the fact that time is used as aninitializer? Something like this comes out.

 1 3 5 6 9 1 4 5 7 8 1 2 4 6 7.

      

I would like to get completely random numbers, for example

1 9 1 3 8 2 1 7 6 7 5...

      

Thanks for any help

+2


source to share


4 answers


You srand()

only need to call once for each program.



+8


source


Also check out Boost's random number library:



Boost Random Number Library

+3


source


  • srand () must be executed once per execution, not once for each rand () call.
  • Some random number generators have a problem with using the "least significant digit" and there is an offset, if you don't drop any number, maybe you can do without problems:

    int alea(int n){ 
       assert (0 < n && n <= RAND_MAX); 
       int partSize = 
         n == RAND_MAX ? 1 : 1 + (RAND_MAX-n)/(n+1); 
       int maxUsefull = partSize * n + (partSize-1); 
       int draw; 
       do { 
          draw = rand(); 
       } while (draw > maxUsefull); 
       return draw/partSize; 
    }
    
          

+1


source


You can use the Park-Miller Peace Standard Linear Congruential Generator (LCG): (seed * 16807 mod (2 ^ 31 - 1)). My implementation is here Random integers with g ++ 4.4.5

The C function srand () is used to set the global variable used by rand (). When you need one sequence of random numbers, "rand ()" is more than sufficient, but often you will need multiple random number generators. In these cases, I would suggest using C ++ and a class like rand31pmc.

If you want to generate random numbers in a small range, then you can use the Java library implementation available here: http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt%28int % 29

0


source







All Articles