I'm currenlty studying PRNG, and I found that there are two function, rand()
and random()
, in GNU/Linux. According to the GNU C Library section 19.8.2, this function, random()
, is just for supporting BSD compatibility. Here are my questions:
random()
? (I can only find rand()
in glibc)I've tried to fix the seed parameter, and the order of the random number from rand()
and random()
are the same in my PC. So, I started to find where rand()
and random()
are implemented in glibc. Eventually, I can only found the implementation of rand()
, and the prototype of random()
in stdlib/stdlib.h (this is not official mirror).
I also try to find it in the linux source code, but still, there is no implementation of random()
. Is there anything I missed?
Edit1:
(Source code of random()
prototype)
/* These are the functions that actually do things. The `random', `srandom',
`initstate' and `setstate' functions are those from BSD Unices.
The `rand' and `srand' functions are required by the ANSI standard.
We provide both interfaces to the same random number generator. */
/* Return a random long integer between 0 and RAND_MAX inclusive. */
extern long int random (void) __THROW;
Answer:
Yes, they're identically the same in glibc. The reason why they are the same is because weak_alias (__random, random)
in random.c, which eventually use the GNU C extension called alias
.
They are currently the same in glibc. However, you should use random()
and not rand()
. The reason is that historically the implementation of rand()
was not the same and was an extremely poor random number generator. From cppreference:
There are no guarantees as to the quality of the random sequence produced. In the past, some implementations of rand() have had serious shortcomings in the randomness, distribution and period of the sequence produced (in one well-known example, the low-order bit simply alternated between 1 and 0 between calls).
Depending on what you are compiling on, you could end up with an old, low-quality rand()
. It's a crap shoot, so don't use it.
The one drawback is that random()
is a POSIX function, not a standard C function. You will generally find random()
everywhere, except on Windows Visual C. There you should use rand_s()
instead of rand()
.
For something truly portable and consistent, you could avoid libraries entirely and include the random number generator in your code. The PCG family of generators provide very high-quality random numbers, better than even some modern library generators, and with very fast and compact code.
The C++ standard defines and requires high-quality random number generators, found in #include <random>
. In C++, those are a very good choice for both portability and quality.
Depending on your application, most of these have issues. See https://www.pcg-random.org/other-rngs.html . Also consider how a pseudo-random generator is seeded. Most operating systems provide truly-random data that can be used for that.