0
srand(time(NULL));
for (it=hand.begin(); it < hand.end(); it++)
    (*it) = rand() % 13 + 1;

This code does not work to create many random numbers at a time. Is there a way to do it that isn't as complex as Mersennes and isn't operating system dependent?

Dash
  • 17,188
  • 6
  • 48
  • 49
  • I think this sentence *"This code does not work to create many random numbers at a time"* ....is not clear enough! – Nawaz Apr 16 '11 at 17:19
  • 1
    Duplicated many times. You only seed (i.e. call `srand`) ***once***. Then you just call `rand` over and over again. Essentially all PRNG work that way. – dmckee --- ex-moderator kitten Apr 16 '11 at 17:19
  • 1
    Where's that xkcd? ... [Ah! :)](http://xkcd.com/221/) – pmg Apr 16 '11 at 17:20
  • 2
    @pmg: This [xkcd](http://xkcd.com/221/)? – Ben Voigt Apr 16 '11 at 17:22
  • I just realized I posted the code wrong! I'm not seeding rand more than once. I'm seeding it once and then when generating many random numbers in a row they all come out the same because they're based on the current second. – Dash Apr 16 '11 at 17:25
  • Duplicate: http://stackoverflow.com/questions/4859089/always-repeated-numbers-given-by-rand Near duplicate here: http://stackoverflow.com/questions/1068350/random-number-function-is-misfiring and http://stackoverflow.com/q/3159644/2509 – dmckee --- ex-moderator kitten Apr 16 '11 at 17:32
  • @Dash: srand() is called ONCE. Put it in main. Call it on entry and never touch it again. As long as your application is not called more than once a second you will not repeat the numbers for the next 60 years. – Martin York Apr 16 '11 at 18:20

5 Answers5

4

PRNGs don't create many PRNs at once. Each output is dependent on the previous output, PRNGs are highly stateful.

Try:

srand(time(NULL)); // once at the start of the program

for( int i = 0; i < N; ++i )
    r[i] = rand();

Even APIs that return an entire block of output in a single function call, have just moved that loop inside the function.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
2

Call srand just once, at the start of your program. Then call rand() (not srand(rand())) to generate each random number.

Anomie
  • 92,546
  • 13
  • 126
  • 145
1

Boost.Random has lots of good random number generators which are easy to use.

Benjamin Bannier
  • 55,163
  • 11
  • 60
  • 80
0

George Marsaglia posted a Multiply With Carry PRNG some time ago in sci.math.

I cannot say how good it is or how well it behaves, but you might want to give it a try.

It should be OS and platform independent.

pmg
  • 106,608
  • 13
  • 126
  • 198
0

"please make sure you answer the question" OK

for (int i=n1; i < n2; ++i)
  { 
  int k; 
  do k = rand(); while (i !=k); 
  // k is a sequential pseudo random number
  }

There may be issues with efficiency...

phunctor
  • 599
  • 3
  • 9