There's a lot of conflicting information about this topic. So let's try to agree on a definitive answer:
Which one of these random number generator in C create better randomness: rand, random or arc4random?
note: Just to make the question clear, this is not a question about true randomness, it's only a clash between those 3.
As pointed out, this question doesn't make much sense, as this is not about C, but about a specific implementation, in my case, cocoa (more specifically the iphone sdk, but my guess is they are the same as far as these functions go). Still, there's some useful information here. I concluded by implementing arc4random, mostly because of its ease of use (no seeding needed), which is an important factor that no one pointed out.
I'm closing the question, and adding the cocoa tag for cocoa developers looking for information on RNGs. Many thanks for those who contributed, and sorry for the confusion.
Of these functions, only rand is part of standard C. random is part of POSIX, and arc4random is only provided in BSD (and derived). So only rand is "in C".
For rand, the C standard says nothing about the quality of the generator, i.e. returning always the same number would be conforming. It says that the number must be between 0 and RAND_MAX. The value of RAND_MAX, and the precise algorithm being used, are implementation defined (although RAND_MAX must be at least 32767).
For random, POSIX specifies that it must have a period of atleast 2^31 by default, and, if initstate is called with 256 bytes of state, then it must have a period of atleast 2^69; other details are again implementation-defined.
For arc4random, the specific implementation is part of its definition (RC4). It's specified that it gives 2^32 different values; I could not find anything about its period.
To compare them in detail, one would have to know what specific implementation you refer to.
The implementation of rand() is not specified by the C standard, however most compilers use a linear congruential generator. random() and arc4random() aren't standard C either, but they are better than the usual implementation of rand()
I'd say: arc4random() is better than random() is better than rand()
rand() is really terrible. You could easily do better than all three however.
It also depends what you want the random numbers for. A good random number generator for encryption/security may not be a good random number generator for simulation and vice-versa.
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