Difference between revisions of "cpp/numeric/random/srand"
(Added links) |
m (fmt) |
||
Line 7: | Line 7: | ||
Seeds the pseudo-random number generator used by {{lc|std::rand()}} with the value {{tt|seed}}. | Seeds the pseudo-random number generator used by {{lc|std::rand()}} with the value {{tt|seed}}. | ||
− | If {{ | + | If {{lc|std::rand()}} is used before any calls to {{tt|srand()}}, {{lc|std::rand()}} behaves as if it was seeded with {{c|srand(1)}}. |
− | Each time {{ | + | Each time {{lc|std::rand()}} is seeded with the same {{tt|seed}}, it must produce the same sequence of values. |
{{tt|srand()}} is not guaranteed to be thread-safe. | {{tt|srand()}} is not guaranteed to be thread-safe. | ||
Line 25: | Line 25: | ||
It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers. | It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers. | ||
− | Standard practice is to use the result of a call to {{c|time(0)}} as the seed. | + | Standard practice is to use the result of a call to {{c|std::time(0)}} as the seed. |
− | However, {{ | + | However, {{lc|std::time}} returns a {{c|std::time_t}} value, and {{c|std::time_t}} is not guaranteed to be an integral type. |
− | In practice, though, every major implementation defines {{ | + | In practice, though, every major implementation defines {{c|std::time_t}} to be an integral type, and this is also what POSIX requires. |
===Example=== | ===Example=== |
Revision as of 16:30, 28 November 2021
Defined in header <cstdlib>
|
||
void srand( unsigned seed ); |
||
Seeds the pseudo-random number generator used by std::rand() with the value seed
.
If std::rand() is used before any calls to srand()
, std::rand() behaves as if it was seeded with srand(1).
Each time std::rand() is seeded with the same seed
, it must produce the same sequence of values.
srand()
is not guaranteed to be thread-safe.
Contents |
Parameters
seed | - | the seed value |
Return value
(none)
Notes
Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand()
, at the start of the program.
It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.
Standard practice is to use the result of a call to std::time(0) as the seed. However, std::time returns a std::time_t value, and std::time_t is not guaranteed to be an integral type. In practice, though, every major implementation defines std::time_t to be an integral type, and this is also what POSIX requires.
Example
Possible output:
Random value on [0 2147483647]: 1373858591
See also
generates a pseudo-random number (function) | |
maximum possible value generated by std::rand (macro constant) | |
reseeds the per-thread random engine (function) | |
C documentation for srand
|