Why does my C random number generator only return

2019-07-21 22:19发布

问题:

As awesome an accidental feature as this is, it makes for a lousy way to "shuffle" an array of "cards". The fact that I'm getting the same number tells me I've having some problem in picking separate seeds each time. Am I using srand48 or the time(NULL) call improperly? Is there some underlying logic flaw I'm missing? Is there just not enough time inbetween iterations for the value of time() to be different?

The code is being run on Linux.

void shuffle()

{
  int i_rnd;   /* Integer random number, range 0..100 */
  int i_rnd2;
  card tempCard; /*temporary card to facillitate swapping*/
  int i = 0; /*can't use a FOR loop 'cause we're not using c99 standard*/
  while(i < 1000)
  {

      srand48( (unsigned) time( NULL ) );  /* Seed the random number generator */
      i_rnd = (int) ( drand48() * 100);
      i_rnd = i_rnd%52; // return a random number 0-51    
      i_rnd2 = (int) ( drand48() * 100);
      i_rnd2 = i_rnd2%52; // return a random number 0-51
      /*we have two random numbers, now exchange the two objects with the
      / picked array indices */
      tempCard =  cardDeck[i_rnd];
      cardDeck[i_rnd]=cardDeck[i_rnd2];
      cardDeck[i_rnd2]=tempCard;
      //swap complete. increment counter so we can eventually get out of the while
      i++;

  }

return;

}

回答1:

You need to seed the pseudorandom number generator once, not every time you use it.

Many (most?) pseudorandom number generators (PRNG) are deterministic given a certain seed value. If time() returns the same value each time your loop executes, you seed the PRNG with the same value just before you use it each time, so when you query it for random numbers it returns the same values.



回答2:

Because you're seeding your random number generator every time through the loop with the same seed (it runs in less than a second). Call srand48() ONCE at the beginning of your program.



回答3:

The PRNG is always deterministic...The randomness of PRNG is not attained by the Logic of it but by the seed it uses.

Therefore make that Seed as Random as possible inorder to achieve Randomness.



标签: c linux random