8

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

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Xavier
  • 8,828
  • 13
  • 64
  • 98

3 Answers3

17

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
7

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

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
2

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:

Community
  • 1
  • 1
Ali
  • 56,466
  • 29
  • 168
  • 265