mercredi 23 mars 2022

How to understand "a given random-number generator always produces the same sequence of numbers" in C++ primer 5th?

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?




Aucun commentaire:

Enregistrer un commentaire