The implementation of rand
in mainstream C standard libraries may be adequate for casual use of pseudorandom numbers (such as in most single-player games, or for aesthetic purposes), especially if your application doesn't care about repeatable "randomness" across time or across computers. (But note that the rand
specification in the C standard doesn't specify a particular distribution that the numbers delivered by rand
have to follow.)
However, for more serious use of pseudorandom numbers, such as in a scientific simulation, I refer you to another answer of mine, where I explain that the problem with rand
/srand
is that rand
—
- Uses an unspecified RNG algorithm, yet
- allows that RNG to be initialized with
srand
for repeatable "randomness".
These two points, taken together, hamper the ability of implementations to improve on the RNG's implementation; changing that RNG will defeat the goal of repeatable "randomness", especially if an application upgrades to a newer version of the C runtime library by the same vendor or is compiled with library implementations by different vendors. The first point also means that no particular quality of pseudorandom numbers is guaranteed. Another problem is that srand
allows for only relatively small seeds — namely those with the same size as an unsigned
.
However, even if the application doesn't care about repeatable "randomness", the fact that rand
specifies that it behaves by default as though srand(1)
were called (and thus, in practice, generates the same pseudorandom sequence by default) makes using rand
harder to use effectively than it could be.
A better approach for noncryptographic pseudorandom numbers is to use a PRNG library—
- that uses self-contained PRNGs that maintain their own state (e.g., in a single
struct
) and don't touch global state, and
- that implements a PRNG algorithm whose details are known to the application.
I list several examples of high-quality PRNG algorithms for noncryptographic pseudorandom numbers.