Цей заголовок представляє засоби генерації випадкових чисел. Ця бібліотека дозволяє створювати випадкові числа за допомогою комбінацій генераторів і розподілів.
- Розподіл : об’єкти, які перетворюють послідовності чисел, згенеровані генератором, у послідовності чисел, що відповідають певному розподілу випадкових величин, наприклад рівномірному нормальному або біноміальному.
Генератори
I. Механізми псевдовипадкових чисел: Вони використовують алгоритм для генерації випадкових чисел на основі початкового початкового числа. Це:

1. linear_congruential_engine : це найпростіший механізм у бібліотеці STL, який генерує випадкові цілі числа без знаку. З цього випливає:
підключити базу даних java
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; }
Вихід:
211182246 is a random number between 1 and 2147483646
2. mersenne_twister_engine: Це система випадкових чисел на основі алгоритму Мерсенна Твістера. Він створює високоякісні випадкові цілі числа без знаку в інтервалі [0 (2^w)-1].
де «w» — розмір слова: кількість бітів кожного слова в послідовності станів.
// 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; }
Вихід:
3348201622 is a random number between 0 and 4294967295
3. subtract_with_carry_engine: Це механізм генератора псевдовипадкових чисел, який створює цілі числа без знаку.
Використовується алгоритм із відставанням генератор фібоначчі з послідовністю станів із r цілих елементів плюс одне значення переносу.
array.sort у java
// 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; }
Вихід:
8606455 is a random number between 0 and 16777215
II. Генератор випадкових чисел : Це генератор випадкових чисел, який створює недетерміновані випадкові числа.
// 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; }
Вихід:
default random_device characteristics: minimum: 0 maximum: 4294967295 entropy: 0 a random number: 3705944883
III. Механізми псевдовипадкових чисел (екземпляри) : Це конкретні екземпляри генераторних двигунів і адаптерів:

1. default_random_engine : це клас двигуна випадкових чисел, який генерує псевдовипадкові числа.
Функція змінює внутрішній стан на один, який змінює значення стану відповідно до заданого алгоритму:
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; }
Вихід:
201066682 is a random number between 1 and 2147483646
2. minstd_rand: Він генерує псевдовипадкові числа; це схоже на лінійний конгруентний генератор
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; }
Вихід:
489592737 is a random number between 1 and 2147483646
3.MT19937: Це генератор Mersenne Twister 19937. Це псевдовипадковий генератор 32-розрядних чисел із розміром стану 19937 біт.
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; }
Вихід:
оператор verilog case
1445431990 is a random number between 0 and 4294967295
4. ranlux24_base: Це базовий генератор Ranlux 24. Це псевдовипадковий генератор 24-розрядних чисел із відніманням і переносом, який зазвичай використовується як базовий механізм для генератора ranlux24.
Функція змінює внутрішній стан, викликаючи свій алгоритм переходу, який застосовує до елемента операцію віднімання з переносом.
// 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; }
Вихід:
7275352 is a random number between 0 and 16777215
Подібний формат застосовний для інших прикладів.
IV. Адаптери двигуна

1. discard_block_engine: Це шаблон класу адаптера двигуна, який адаптує a Двигун генератора псевдовипадкових чисел типу, використовуючи лише елементи 'r' кожного блоку елементів 'p' із створеної послідовності, відкидаючи решту.
Адаптер веде внутрішній підрахунок кількості елементів, створених у поточному блоці.
hashmap
Стандартні генератори ranlux24 і ranlux48 адаптувати a subtract_with_carry_engine за допомогою цього адаптера.
// 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; }
Вихід:
8132325 is a random number between 0 and 16777215
2. independent_bits_engine: Це шаблон класу адаптера двигуна, який адаптує a Двигун генератора псевдовипадкових чисел типу для створення випадкових чисел із певною кількістю бітів (w).
Алгоритм переходу двигуна викликає оператор () базового механізму стільки разів, скільки потрібно, щоб отримати достатню кількість значущих бітів для побудови випадкового значення.
// 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; }
Вихід:
13551674127875514537 is a random number between 0 and 184467
3. shuffle_order_engine: Це шаблон класу адаптера двигуна, який адаптує a Двигун генератора псевдовипадкових чисел введіть так, щоб числа відображалися в іншій послідовності.
Об’єкт зберігає буфер із k згенерованих чисел усередині та за запитом повертає випадково вибране число в буфері, замінюючи його значенням, отриманим із його основного механізму.
Алгоритм переходу механізму вибирає значення у внутрішній таблиці (яке повертає функція) і замінює його новим значенням, отриманим від його базового механізму.
// 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; }
Вихід:
9213395 is a random number between 0 and 16777215Створіть вікторину