Using srand () in C ++

I'm new to C ++, so this doubt may look fundamentally, but I don't get the difference between rand () and srand (), and what does u mean as a β€œseed” in srand ()? when I write srand (time (NULL)), what does it do to generate random numbers, what does time (NULL) do here? So what is this? thanks in advance

+6
source share
2 answers

The random number generator requires a number (it is called seed) to generate random numbers. If the random number generator is given the same seed, then each time it will generate the same sequence of random numbers. For instance: -

If you run the program and generate a random sequence of 2.78.45.60. If the second time you run the program, you will again get the same sequence 2.78.45.60.

The srand function is used to change the seed of a random number generator. When setting srand (time (NULL)), you set the seed of the random number generator to the current time. By doing this every time you run, you will get different random sequences: -

For example, for the first run, if you get 2.78.45.60. Next time you can get 5,3,6,80 (depending on the current time, since the seed has been changed since the time has changed since the last run)

for more information see the following: -

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/

http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

http://www.cplusplus.com/reference/clibrary/ctime/time/

+9
source

rand() does not produce a random number - it uses some fairly light formula to calculate the next "random value" based on its stored internal state, which changes every time a random value is generated. srand() sets this internal state.

That way you can get reproducible sets of numbers - you call srand() with the given value and rand() then returns a set of values. The next time you run the program and call srand() with exactly the same rand() value, you will get the exact same set of values. This is useful for modeling.

Calling srand( time( NULL ) ) forces your program to generate a set of values ​​that will depend on the current time and, therefore, be perfect - each time you restart the program, a new set of numbers is generated.

+7
source

Source: https://habr.com/ru/post/885645/


All Articles