隨機化算法之隨機數
阿新 • • 發佈:2018-05-20
整數 for stat cpp 隨機化算法 ons 系統時間 硬幣 head
首先是介紹:
代碼如下:
//隨機數類 //Random.hpp //===================================================== #ifndef RANDOM_HPP #define RANDOM_HPP #include<ctime> const unsigned long maxshort = 65536L; const unsigned long multiplier = 1194211693L; const unsigned long adder = 12345L; class RandomNumber{private: //當前種子 unsigned long randSeed; public: RandomNumber(){}; RandomNumber(unsigned long s = 0); //構造函數,默認值0表示由系統自動產生種子 unsigned short Random(unsigned long n); //產生0:n-1之間的隨機整數 double fRandom(void); //產生[0 , 1)之間的隨機整數 }; RandomNumber::RandomNumber(unsigned long s) //產生種子{ if (s == 0) { randSeed = time(0); //使用系統時間產生隨機種子 } else { randSeed = s; } } unsigned short RandomNumber::Random(unsigned long n) //產生 0:n-1之間的隨機整數 { randSeed = multiplier * randSeed + adder; return(unsigned short)((randSeed >> 16) % n); }double RandomNumber::fRandom(void) //產生[0 , 1)之間的隨機數 { return Random(maxshort) / double(maxshort); } #endif
//隨機數 //main.cpp //============================================== #include <iostream> #include <iomanip> #include "Random.hpp" using namespace std; int TossCoins(int numberCoins) { //隨機拋硬幣 static RandomNumber coinToss(0); int tosses = 0; for (int i = 0; i < numberCoins; i++) { tosses += coinToss.Random(2); } return tosses; } int main(void) { //模擬隨機拋硬幣事件 const int NCOINS = 10; const long NTOSSES = 50000L; //heads[i]是得到i次正面的次數 long heads[NCOINS + 1]; int position; //初始化數組heads for (int i = 0; i < NCOINS + 1; i++) { heads[i] = 0; } //重復50000次試驗 for (int j = 0; j < NTOSSES; j++) { heads[TossCoins(NCOINS)] ++; } //輸出頻率圖 for (int i = 0; i < NCOINS; i++) { position = int(float(heads[i]) / NTOSSES * 72); cout << setw(6) << i << " "; for (int j = 0; j < position - 1; j++) { cout << " "; } cout << "*" << endl; } system("pause"); }
結果如下(頻率圖):
隨機化算法之隨機數