srand(time(0))
is used in C++ to help in the generation of random numbers by seeding rand with a starting value.
But, can you explain what it exactly does?
Thanks.
time(0) gives the time in seconds since the Unix epoch, which is a pretty good "unpredictable" seed (you're guaranteed your seed will be the same only once, unless you start your program multiple times within the same second).
The srand() function sets the starting point for producing a series of pseudo-random integers. If srand() is not called, the rand() seed is set as if srand(1) were called at the program start. Any other value for seed sets the generator to a different starting point.
The generation of the pseudo-random number depends on the seed. If you don't provide a different value as seed, you'll get the same random number on every invocation(s) of your application. That's why, the srand() is used to randomize the seed itself.
C++ Random Number Between 0 And 1 We can use srand () and rand () function to generate random numbers between 0 and 1. Note that we have to cast the output of rand () function to the decimal value either float or double.
srand()
gives the random function a new seed, a starting point (usually random numbers are calculated by taking the previous number (or the seed) and then do many operations on that number to generate the next).
time(0)
gives the time in seconds since the Unix epoch, which is a pretty good "unpredictable" seed (you're guaranteed your seed will be the same only once, unless you start your program multiple times within the same second).
From what I remember, there is an equation that is used to generate a sequence of values. The next value is somewhat influenced by the previous value. By using the time, you are setting the initial value of the equation. Keep in mind, the values are pseudo random.
So for example, if you do something like this:
srand(1);
srand(1);
The same sequence of numbers will be generated. However, if you do:
srand(time(0));
srand(time(0) + 1);
Two different sequences of numbers will b e generated because the seed value is different.
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