How can I generate different random numbers at runtime?
I've tried
srand((unsigned) time(0));
But it seems to get me a random number on every startup of the program, but not on every execution of the function itself...
I'm trying to automate some tests with random numbers, random iterations, number of elements, etc... I thought I could just call
srand((unsigned) time(0));
at the beginning of my test function and bingo, but apparently not.
What would you suggest me to do?
A random seed is a starting point in generating random numbers. A random seed specifies the start point when a computer generates a random number sequence. This can be any number, but it usually comes from seconds on a computer system's clock (Henkemans & Lee, 2001).
Seed function is used to save the state of a random function, so that it can generate same random numbers on multiple executions of the code on the same machine or on different machines (for a specific seed value). The seed value is the previous value number generated by the generator.
The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used. The srand() function sets the initial point for generating the pseudo-random numbers.
A random seed (or seed state, or just seed) is a number (or vector) used to initialize a pseudorandom number generator. In other word, it is the number from which a seem-to-be-random sequence will be generated. Therefore, if you use the same number, the senquence will always be the same.
As others have mentioned. srand() seeds the random number generator. This basically means it sets the start point for the sequence of random numbers. Therefore in a real application you want to call it once (usually the first thing you do in main (just after setting the locale)).
int main()
{
srand(time(0));
// STUFF
}
Now when you need a random number just call rand().
Moving to unit testing. In this situation you don;t really want random numbers. Non deterministic unit tests are a waste of time. If one fails how do you re-produce the result so you can fix it?
You can still use rand() in the unit tests. But you should initialize it (with srand()) so that the unit tests ALWAYS get the same values when rand() is called. So the test setup should call srand(0) before each test (Or some constant other than 0).
The reason you need to call it before each test, is so that when you call the unit test framework to run just one test (or one set of tests) they still use the same random numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With