Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: the definitive truth about rand, random and arc4random [closed]

Tags:

c

random

cocoa

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.

like image 677
Steph Thirion Avatar asked Nov 30 '08 15:11

Steph Thirion


2 Answers

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.

like image 108
Martin v. Löwis Avatar answered Oct 27 '22 00:10

Martin v. Löwis


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.

like image 40
Roland Rabien Avatar answered Oct 26 '22 23:10

Roland Rabien