As far as I know rand() does not generate a uniform random distribution. What function/algorithm will allow me to do so? I have no need for cryptographic randomness, only a uniform random distribution. Lastly, what libraries provide these functions?
Thanks!
As far as I know rand() does not generate a uniform random distribution. What
Share
rand()does generate a uniform (pseudo-)random distribution.The actual requirement, from the C standard (3.7 MB PDF), section 7.20.2.1, is:
where RAND_MAX is at least 32767. That’s admittedly vague, but the intent is that it gives you a uniform distribution — and in practice, that’s what implementations actually do.
The standard provides a sample implementation, but C implementations aren’t required to use it.
In practice, there are certainly better random number generators out there. And one specific requirement for
rand()is that it must produce exactly the same sequence of numbers for a given seed (argument tosrand()). Your description doesn’t indicate that that would be a problem for you.One problem is that
rand()gives you uniformly distributed numbers in a fixed range. If you want numbers in a different range, you have to do some extra work. For example, if RAND_MAX is 32767, thenrand()can produce 32768 distinct values; you can’t get random numbers in the range 0..9 without discarding some values, since there’s no way to evenly distribute those 32768 distinct values into 10 equal sized buckets.Other PRNGs are likely to give you better results than
rand(), but they’re still probably going to be subject to the same issues.As usual, the comp.lang.c FAQ answers this better than I did; see questions 13.15 through 13.21.