Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the <random> library in c++11 portable?

Tags:

c++

random

c++11

Is the library in c++11 portable? I have avoided rand() because I heard it wasn't portable.

like image 350
Xavier Avatar asked Feb 12 '13 20:02

Xavier


People also ask

What library is the rand function in?

C library function - rand() The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX.

What is random function in C?

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.

What does rand() return C++?

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.

How do you generate random bytes in C++?

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.


3 Answers

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.

like image 151
Nicol Bolas Avatar answered Oct 12 '22 04:10

Nicol Bolas


The random number engines described in <random> have explicit requirements for their algorithms to ensure portability. The distributions do not.

like image 20
Pete Becker Avatar answered Oct 12 '22 03:10

Pete Becker


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

like image 2
Ali Avatar answered Oct 12 '22 02:10

Ali