Kadiro
Kadiro

Reputation: 11

How randomness is when initializing the c/c++ seed with small values and a higher one?

I am using srand() in order to have some pseudo-randomness in my c/c++ program.

I was wondering about whether a srand(1) and srand(2) have a randomness much like, lets say, srand(21254) and srand(9897455)?

Because, I was running my program with small different numbers for the seed, and I have an impression that is unlike!

Best Regards

Upvotes: 1

Views: 254

Answers (2)

Mark Ransom
Mark Ransom

Reputation: 308158

You say in the comments that you don't have the option of choosing a better random number generator. That is a shame, because C++ has the random header since C++11, and it's vastly improved over the old rand/srand.

There's definitely a correlation between the seed you use in srand and the resulting numbers that you pull from rand, that's the whole point of seeding. Some C++ implementations will make this more obvious than others, since the implementation of rand isn't tightly specified and is left to each library.

The simplest way to hide this correlation is to take a few random numbers after seeding and simply throw them away, because the correlation becomes less obvious with each generated number. If it didn't, it wouldn't be an acceptable random number generator.

srand(1);
cout << "throwing away " << rand() << endl;
cout << "throwing away " << rand() << endl;
cout << "using " << rand() << endl;

srand(2);
cout << "throwing away " << rand() << endl;
cout << "throwing away " << rand() << endl;
cout << "using " << rand() << endl;

Upvotes: 0

user439793
user439793

Reputation:

As the comments say, you should be using a real random number library if you are concerned about the quality of random numbers.

srand() and rand() are usually a basic periodic pseudorandom number generator. There will be a fixed sequence of values that cycle, all in a row. If you received 12 as your last number, and receive 600 as your next number, then the next time the cycle rolls back around to 12 you will again receive 600 as your next number.

Therefore, the seed does not affect the "randomness" or quality of the pseudorandom numbers. Calling srand(21254) or srand(9897455) simply starts at different points in the same sequence.

Note: it is possible that a particular implementation of rand() will not use this method: however, it is unlikely and in the absence of any guarantees you are better off with the <random> library which does have guarantees about the methods used to generate random numbers. The classes in that library will produce better quality sequences of random numbers.

Upvotes: 2

Related Questions