user119653
user119653

Reputation:

Random integers c++

I'm trying to produce random integers (uniformly distributed). I found this snippet on an other forum but it works in a very weird way..

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

Using this method I get values in a cycle so the value increases with every call until it goes down again. I guess this has something to do with using the time as aninitializer? Something like this comes out.

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

I would however like to get totally random numbers like

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

Thanks for any help

Upvotes: 2

Views: 584

Answers (4)

Adolfo
Adolfo

Reputation: 339

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

The C language 'srand()' function is used to set the global variable that 'rand()' uses. When you need a single sequence of random numbers, 'rand()' is more than enough, but oftentimes you need several random number generators. For those cases, my advice would be to use 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

Upvotes: 0

ToastedSoul
ToastedSoul

Reputation: 1296

Also check out the Boost Random Number Library:

Boost Random Number Library

Upvotes: 3

AProgrammer
AProgrammer

Reputation: 52334

  • srand() has to be done once per execution, not once for each rand() call,
  • some random number generators have a problem with using "low digit", and there is a bias if you don't drop some number, a possible work around for both issues:

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

Upvotes: 1

Michał G&#243;rny
Michał G&#243;rny

Reputation: 19303

You should call srand() only once per program.

Upvotes: 8

Related Questions