Home > Blockchain >  How to understand "a given random-number generator always produces the same sequence of numbers
How to understand "a given random-number generator always produces the same sequence of numbers

Time:03-24

Title "Engines Generate a Sequence of Numbers" in section 17.4.1 has following Warring.

A given random-number generator always produces the same sequence of numbers. A function with a local random-number generator should make that generator (both the engine and distribution objects) static. Otherwise, the function will generate the identical sequence on each call.

"A given random-number generator always produces the same sequence of numbers." What kind of given generator does it refer to?

If I give a random number engine and a random number distribution, they form a given random number generator.

  1. Will it always produce a fixed sequence of values given a seed?
  2. Won't it change because of different compilers or system environments?

So I compiled and ran the following code on different compilers.

#include <iostream>
#include <random>
using namespace std;

minstd_rand0 dre1(13232);
minstd_rand0 dre2(13232);

int main()
{
    uniform_int_distribution<unsigned> h1(0,10);
    uniform_int_distribution<unsigned> h2(0,10);
    unsigned t=100;
    while(t--){
        cout << "dre1:" << h1(dre1) << endl;
        cout << "dre2:" << h2(dre2) << endl;
    }

}

For it's easy to watch, I won't release all the results.

//in gcc and clang:
dre1:1 
dre2:1 
dre1:5 
dre2:5 
dre1:1 
dre2:1 
dre1:9 
dre2:9 
dre1:6 
dre2:6
//in msvc
dre1:0
dre2:0
dre1:0
dre2:0
dre1:3
dre2:3
dre1:2
dre2:2
dre1:0
dre2:0

Why did this happen?

CodePudding user response:

The random-number facilities that were introduced in C 11 have two categories of things: generators and distributions. Generators are sources of pseudo-random numbers. A distribution takes the results of a generator as input and produce values that meet the statistical requirements for that distribution.

Generators are tightly specified: they must use a particular algorithm with a particular set of internal values. In fact, the specification in the C standard includes the 10,000th value that each default-constructed generator will produce. As a result, they will have the same behavior on all platforms.

Distributions are not tightly specified; their behavior is described in terms of the overall distribution that they provide; they are not required to use any particular algorithm. Code that uses them is portable across all platforms; the values that they produce from the same generator will not necessarily be the same.

A newly-constructed generator object will produce a particular sequence of values as specified by its algorithm. Another newly-constructed generator object will produce exactly the same sequence. So, in general, you want to create one generator object and one distribution object, and use the pair to produce your desired pseudo-random sequence.

  • Related