4

If you look to the specifications of random shuffle in C++11, there are 3 functions. My question is what is the typical use and advantage of :

template< class RandomIt, class URNG >
void shuffle( RandomIt first, RandomIt last, URNG&& g );

compared to:

template< class RandomIt >
void random_shuffle( RandomIt first, RandomIt last );

I mean, it seems that whatever URNG is (a uniform distribution), the result will be the same (from a statistical point of view). The only point I see, is that std::shuffle is thead-safe, whereas this overload ofstd::random_shuffle is not. Could you confirm that ?

EDIT: I thought that URNG should be a uniform distribution but that does not seem to compile. So can someone provide a little example of use of std::shuffle?

Vincent
  • 57,703
  • 61
  • 205
  • 388
  • Well, the first one lets you chose the random number generator. The second one doesn't. – juanchopanza Jul 18 '13 at 13:36
  • 1
    I have a hard time believing that the result is the same. How exactly are you calling `std::shuffle`? – Xeo Jul 18 '13 at 13:37
  • @Xeo, when I say "the same" I mean "statistically the same". – Vincent Jul 18 '13 at 13:40
  • The URNG is a random *engine*, like `std::mt19937`. – Xeo Jul 18 '13 at 13:57
  • @URNG So I missed the "uniform" point. Is there any non-uniform random engine in `` (wathever this means) ? – Vincent Jul 18 '13 at 14:03
  • 1
    @Vincent, you can wrap it into the distribution object e.g. `normal_distribution` instance (see more here http://www.cplusplus.com/reference/random/normal_distribution/) – sasha.sochka Jul 18 '13 at 14:15
  • 1
    You can find a little example of std::shuffle at [cppreference](http://en.cppreference.com/w/cpp/algorithm/random_shuffle) – Cubbi Jul 18 '13 at 14:58

1 Answers1

2

As mentioned in the comments, std::shuffle takes a random number generator (or engine in standard speak), not a random number distribution. Different random number generators have different characteristics even if they have a theoretically uniform distribution.

  • Random or pseudo-random - True random number generators use some sort of an external entropy source. Pseudo-random generators (PRNGs) are strictly deterministic.
  • Performance - some generators are faster than others.
  • Memory usage - some PRNGs need more memory to store their state than others.
  • Period length - all PRNGs have a finite period after which they start repeating the same sequence from the beginning. Some have much longer periods than others.
  • Randomness quality - there are numerous tests for measuring whether there are subtle (or not-so-subtle!) patterns in a pseurorandom stream. See, for example, the Diehard tests.
  • Whether the stream is cryptographically secure or not. AFAIK, none of the standard PRNGs are.

For an overview of the different generators offered by the standard, please refer to http://en.cppreference.com/w/cpp/numeric/random.

JohannesD
  • 13,802
  • 1
  • 38
  • 30