-1

I've just figured out that seeding generator should be done once - e.g. in main function. Function like this:

int getRand(){
    srand ( time(NULL) );
    cout<<((double) rand() / (RAND_MAX))<<" ";
}

calling in main:

int main(){ 
    cout<<getlvl()<<" "<<getlvl()<<" "<<getlvl()<<" "<<getlvl();    
    return 0;
}

gives me the same output all the time. Why srand should be calling only once to work correctly?

Kornelia
  • 43
  • 1
  • 3

1 Answers1

1

Because time(NULL) doesn't have enough resolution. For every call to srand() there is not enough time between the calls and time(NULL) returns the same for every call.

So you are essentially setting the same seed for every call. If you use a more fine grained time function, with nanoseconds precision you might observe a difference.

If you call srand() once at the beginning of the program, then the seed is set to the current time(NULL) value and every call generates a new pseudo-random value. If you call the program consecutively very quickly you could observe the same problem too.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97