Is the library in c++11 portable? I have avoided rand() because I heard it wasn't portable.
C library function - rand() The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX.
In the C programming language, the rand() function is a library function that generates the random number in the range [0, RAND_MAX]. When we use the rand() function in a program, we need to implement the stdlib. h header file because rand() function is defined in the stdlib header file.
Returns a pseudo-random integral number in the range between 0 and RAND_MAX . This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called.
rand(): rand() function is a predefined method of C++. It is declared in <stdlib. h> header file. rand() is used to generate random number within a range.
How do you define "portable"?
If by "portable", you mean "will produce binary identical sequences of random numbers given the same input", then yes, rand isn't portable. And yes, the C++ random generators are portable (most of them. Not std::default_random_engine or std::random_device), because they implement specific algorithms. rand is allowed to be anything, as long as it's not entirely unlike a random number generator.
That being said, as @PeteBecker pointed out, the distributions themselves are not so well-defined. So while std::mt19937 will produce the same sequence of values for a given seed, different std::uniform_int_distributions can give different values for the same input sequence and range.
Of course, if you need consistency, you can always define your own distribution.
The random number engines described in <random> have explicit requirements for their algorithms to ensure portability. The distributions do not.
You can generate "identical sequences of random numbers given the same input" (from @Nicol Bolas) with std::mt19937 (Mersenne Twister) for example. You definitely couldn't do that with rand() which was quite annoying.
Related questions:
Does the C++11 standard guarantee identical random numbers for the same seed across implementations?
Consistent pseudo-random numbers across platforms
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