Este cabeçalho apresenta recursos de geração de números aleatórios. Esta biblioteca permite produzir números aleatórios usando combinações de geradores e distribuições.
- Distribuições : Objetos que transformam sequências de números geradas por um gerador em sequências de números que seguem uma distribuição de variável aleatória específica, como Normal ou Binomial uniforme.
Geradores
I. Mecanismos de números pseudo-aleatórios: Eles usam um algoritmo para gerar números aleatórios com base em uma semente inicial. Estes são:

1. motor_linear_congruencial : é o mecanismo mais simples da biblioteca STL que gera números inteiros aleatórios sem sinal. Segue:
chave de inserção do laptop
x = (a.x +c) mod m Where x= current state value a = multiplier parameter ; if m is not zero this parameter should be lower than m. c = increment parameter ; if m is not zero this parameter should be lower than m. m = modulus parameter
// C++ program to illustrate // the use of operator() max and min // in linear_congruential_engine #include #include #include using namespace std; // driver program int main () { // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // minstd_rand0 is a standard // linear_congruential_engine minstd_rand0 generator (seed); // generates the random number cout << generator() << ' is a random number between '; //use of min and max functions cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
211182246 is a random number between 1 and 2147483646
2. mersenne_twister_engine: É um mecanismo de números aleatórios baseado no algoritmo Mersenne Twister. Ele produz números aleatórios inteiros sem sinal de alta qualidade no intervalo [0 (2 ^ w) -1].
onde 'w' é o tamanho da palavra: Número de bits de cada palavra na sequência de estado.
// C++ program to illustrate the use of // operator() min and max // in mersenne_twister_engine #include #include #include using namespace std; // Driver program int main () { // finds the time between the system clock // (present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // mt19937 is a standard mersenne_twister_engine mt19937 generator (seed); // use of operator() cout << generator() << ' is a random number between '; // use of max and min cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
3348201622 is a random number between 0 and 4294967295
3. subtrair_com_carry_engine: É um mecanismo gerador de números pseudo-aleatórios que produz números inteiros sem sinal.
O algoritmo usado é um defasado gerador de fibonacci com uma sequência de estados de r elementos inteiros mais um valor de transporte.
// C++ program to illustrate the use of // operator() min and max // in subtract_with_carry_engine #include #include #include using namespace std; // Driver program int main () { // finds the time between the system clock // (present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); subtract_with_carry_engine<unsigned 24 10 24> generator (seed); // use of operator() cout << generator() << ' is a random number between '; // use of min and max cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
8606455 is a random number between 0 and 16777215
II. Gerador de números aleatórios : É um gerador de números aleatórios que produz números aleatórios não determinísticos.
histórico de versões do Android
// C++ program to illustrate the use of // operator() min and max // in random_device #include #include using namespace std; //Driver program int main () { random_device example; cout << 'default random_device characteristics:' << endl; // use of min cout << 'minimum: ' << example.min() << endl; // use of max cout << 'maximum: ' << example.max() << endl; // use of entropy cout << 'entropy: ' << example.entropy() << endl; // use of operator() cout << 'a random number: ' << example() << endl; return 0; }
Saída:
default random_device characteristics: minimum: 0 maximum: 4294967295 entropy: 0 a random number: 3705944883
III. Mecanismos de números pseudo-aleatórios (instanciações) : Estas são as instanciações específicas de motores geradores e adaptadores:

1.default_random_engine : esta é uma classe de mecanismo de números aleatórios que gera números pseudo-aleatórios.
A função altera o estado interno por um que modifica o valor do estado de acordo com o algoritmo fornecido:
x= (a.x + c)mod m Where x= current state value a and c = respective class template parameters m = class template parameterC++
// C++ program to illustrate the use of // operator() min and max // in default_random_engine #include #include #include using namespace std; // Driver program int main () { // finds the time between the system clock // (present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // minstd_rand0 is a standard linear_congruential_engine minstd_rand0 generator (seed); // generates the random number cout << generator() << ' is a random number between '; // Use of min and max cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
201066682 is a random number between 1 and 2147483646
2.minstd_rand: Gera números pseudoaleatórios; é semelhante a gerador congruente linear
x = (a.x + c) mod m where x= current state value a c and m=class template parameter
// C++ program to illustrate // the use of operator() max and min // in minstd_rand #include #include #include using namespace std; //Driver program int main () { // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // minstd_rand0 is a standard //linear_congruential_engine minstd_rand0 generator (seed); // use of operator() cout << generator() << ' is a random number between '; //use of max and min cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
489592737 is a random number between 1 and 2147483646
3.MT19937: É o gerador Mersenne Twister 19937. É um gerador pseudo-aleatório de números de 32 bits com um tamanho de estado de 19.937 bits.
tamanho do vetor c++
C++
// C++ program to illustrate the // use of operator()min and max // in mt19937 #include #include #include using namespace std; // Driver program int main () { // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // mt19937 is a standard //mersenne_twister_engine mt19937 generator (seed); //use of operator() cout << generator() << ' is a random number between '; //use of max and min cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
1445431990 is a random number between 0 and 4294967295
4. ranlux24_base: É um gerador de base Ranlux 24. É um gerador pseudo-aleatório de subtração com transporte de números de 24 bits, geralmente usado como mecanismo base para o gerador ranlux24.
A função altera o estado interno chamando seu algoritmo de transição que aplica uma operação de subtração com transporte no elemento.
// C++ program to illustrate // the use of operator()min and max // in ranlux24_base #include #include #include using namespace std; //Driver program int main () { // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); subtract_with_carry_engine<unsigned241024> generator (seed); //use of operator() cout << generator() << ' is a random number between '; //use of max and min cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
7275352 is a random number between 0 and 16777215
Formato semelhante é aplicável aos outros exemplos.
4. Adaptadores de motor

1. descarte_block_engine: É um modelo de classe de adaptador de mecanismo que adapta um Motor gerador de números pseudo-aleatórios digite usando apenas elementos 'r' de cada bloco de elementos 'p' da sequência que produz descartando o resto.
O adaptador mantém uma contagem interna de quantos elementos foram produzidos no bloco atual.
Os geradores padrão ranlux24 e ranlux48 adaptar um subtrair_com_carry_engine usando este adaptador.
// C++ program to illustrate // the use of operator()min and max // in the discard_block_engine #include #include #include using namespace std; //Driver program int main () { // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // ranlux24 is a standard instantiation //of discard_block_engine: ranlux24 generator (seed); //use of operator() cout << generator() << ' is a random number between '; //use of max and min cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
conversão de int para string
8132325 is a random number between 0 and 16777215
2. motor_bits_independente: É um modelo de classe de adaptador de mecanismo que adapta um Motor gerador de números pseudo-aleatórios digite para produzir números aleatórios com um número específico de bits (w).
O algoritmo de transição do mecanismo invoca o membro operador() dos mecanismos base quantas vezes forem necessárias para obter bits significativos suficientes para construir um valor aleatório.
// C++ program to illustrate // the use of operator()min and max // in independent_bits_engine #include #include // It imports the symbol names in // std namespace and possibly in Global namespace. #include #include using namespace std; //Driver program int main () { // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); //use of independent_bits_engine independent_bits_engine<mt1993764uint_fast64_t> generator (seed); //use of operator() cout << generator() << ' is a random number between '; //use of max and min cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
13551674127875514537 is a random number between 0 and 184467
3. shuffle_order_engine: É um modelo de classe de adaptador de mecanismo que adapta um Motor gerador de números pseudo-aleatórios digite para que os números sejam entregues em uma sequência diferente.
O objeto mantém internamente um buffer de k números gerados e quando solicitado retorna um número selecionado aleatoriamente dentro do buffer substituindo-o por um valor obtido de seu mecanismo base.
O algoritmo de transição do mecanismo escolhe um valor na tabela interna (que é retornado pela função) e o substitui por um novo valor obtido de seu mecanismo base.
// C++ program to illustrate // the use of operator()min and max // in shuffle_order_engine #include #include #include using namespace std; int main () { // finds the time between the system clock //(present time) and clock's epoch unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // ranlux24 is a standard instantiation // of discard_block_engine: ranlux24 generator (seed); //use of operator() cout << generator() << ' is a random number between '; //use of max and min cout << generator.min() << ' and ' << generator.max(); return 0; }
Saída:
9213395 is a random number between 0 and 16777215Criar questionário