Hello a111poudel,
There are some things in C++ that only need to be done
once in a program. Like:
srand(static_cast<size_t>(time(nullptr)));
,
std::default_random_engine engine{ seed };
and
std::cout << std::fixed << std::showpoint << std::setprecision(2);
. These are usually done near the beginning of "main".
The way "srand()" and "rand" work is "srand()" sets up the start of generating a random number and each call to "rand" uses the previously generated random number to create the next, as I understand it. Each time you call "srand()" , say in a function, you
may be giving a new number to the RNG, but you are essentially starting over and the RNG does not have the chance to use its function(s) to create a new random number. Also a function can be called quickly enough so that the value returned from the call to "time()" could be the same number thus you could generate the same random number two or more times before it changes.
In the above line of code for "srand()" notice the use of "nullptr". Although (0) zero and "NULL" will work I read some time back, and still trying to find where, that "nullptr" is the best choice when you want "time()" to return a number.
If I am passing time(0), whose value changes every second
|
Not really when you consider that the computer can execute many instructions in the time of milliseconds. A call to "time()" could happen many times before "time()" would return a new value. Thus you could be giving "srand()" the same number to start with and if you look at a greater range of numbers, say 100, you would see the same numbers several times before they would change.
From
http://www.cplusplus.com/reference/cstdlib/srand/?kw=srand
For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.
Hope that helps,
Andy
|