# 亂數 2021 grorge --- ### 亂數的功用 ~~反正我們也不知道他是甚麼數字~~ 把它拿來當作一個讓程式可以在每次有不同執行結果的數字 比如:抽籤、換座位、~~賭博~~ --- ### 亂數的用法 ```cpp= #include <iostream> #include <cstdlib> //rand的函數庫 using namespace std; int main(){ int a = rand(); cout << a << endl; return 0 } ``` --- ### 更改亂數種子 ```cpp= #include <iostream> #include <cstdlib> //rand的函數庫 #include <ctime> //time的函數庫 using namespace std; int main(){ srand(time(NULL)); int a = rand(); cout << a << endl; return 0 } ``` --- ### 如何檢驗亂數 1.統計學偽隨機性 2.密碼學安全偽隨機性 3.真隨機性 --- ### 偽隨機數 1.統計學偽隨機性 ~~2.密碼學安全偽隨機性 3.真隨機性~~ --- ### Rand 函數 根據C++的[ducumentation](https://en.cppreference.com/w/cpp/numeric/random/rand)裡面有一個常數是RAND_MAX,代表著你亂數能產生的範圍,windows平台大多是32767而linux則是2147483647 --- ### Rand 函數實作 大部分的rand()是用linear congruential generator (LCG)實作的,根據[wiki](https://en.wikipedia.org/wiki/Linear_congruential_generator) ![](https://miro.medium.com/max/483/1*2HBdZwrLH2-uFkSOp48oqw.png) ```cpp= Xn+1 = ((xn * 0xdefaced + 2531011L) & 0x7fffffff) >> 0 ``` --- ### random #### 在C++11後多了random這個函式庫,裡面的東西大致可以分為三類 1. 隨機種子產生器 2. 亂數產生器 3. 機率分佈 --- ### 更多隨機種子產生器 ```cpp= #include <iostream> #include <random> int main(){ /* 隨機設備 */ std::random_device rd; /* 隨機亂數的範圍 */ std::cout << "Min = " << rd.min() << ", Max = " << rd.max() << std::endl; /* 產生隨機的亂數 */ std::cout << "Random Number = " << rd() << std::endl; return 0; } ``` --- ```cpp= #include <iostream> #include <random> int a = 0; int main(){ int k = 0; srand(&a - &k); return 0; } ``` --- ### 亂數產生器 ```cpp= #include <iostream> #include <chrono> #include <random> int main () { unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::mt19937 generator (seed); // mt19937 is a standard mersenne_twister_engine std::cout << generator() << " is a random number between "; std::cout << generator.min() << " and " << generator.max(); return 0; } ``` --- ### 其他亂數產生器 [常態分布](http://www.cplusplus.com/reference/random/normal_distribution/) ![](https://miro.medium.com/max/271/1*0M6X1A0CC7HI7DIUZyZPDg.png) --- ### 來試試看唬爛題目 [codeforces](https://codeforces.com/contest/1454/problem/A) --- ###### tags: `資訊之芽`
{"metaMigratedAt":"2023-06-15T20:26:06.712Z","metaMigratedFrom":"Content","title":"亂數","breaks":true,"contributors":"[{\"id\":\"222f4ab8-a50e-41b7-89a4-dbe2329eaad7\",\"add\":2217,\"del\":9}]"}
    708 views