C++11帶來的隨機數生成器

C++11帶來諸多特性,random就是其一.ios

1. random_device算法

  標準庫提供了一個非肯定性隨機數生成設備.在Linux的實現中,是讀取/dev/urandom設備;Windows的實現竟然是用rand_s,在這裏強烈譴責一下.windows

  random_device提供()操做符,用來返回一個min()到max()之間的一個數字.若是是Linux(Unix Like或者Unix)下,均可以使用這個來產生高質量的隨機數,能夠理解爲真隨機數.dom

#include <iostream>
#include <random>
int main()
{
  std::random_device rd;
  for(int n=0; n<20000; ++n)
    std::cout << rd() << std::endl;
  return 0; 
}

2. random number enginespa

  標準把隨機數抽象成隨機數引擎和分佈兩部分.引擎用來產生隨機數,分佈產生特定分佈的隨機數(好比平均分佈,正太分佈等).code

  標準提供三種經常使用的引擎:linear_congruential_engine,mersenne_twister_engine和subtract_with_carry_engine.第一種是線性同餘算法,第二種是梅森旋轉算法,第三種帶進位的線性同餘算法.第一種是最經常使用的,並且速度也是很是快的; 第二種號稱是最好的僞隨機數生成器;第三種沒用過....orm

  隨機數引擎接受一個整形參數看成種子,不提供的話,會使用默認值. 推薦使用random_device來產生一個隨機數看成種子.(windows下愛咋整咋整,誰叫windows的random_device是調用rand_s)blog

#include <iostream>
#include <random>

int main()
{
  std::random_device rd;
  std::mt19937 mt(rd());
  for(int n = 0; n < 10; n++)
    std::cout << mt() << std::endl;
  return 0;
}

3. random number distributionsip

  標準提供各類各樣的分佈,不過咱們常常用的比較少,好比平均分佈,正太分佈...使用也很簡單ci

//平均分佈
#include <random>
#include <iostream>
int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 6);
    for(int n=0; n<10; ++n)
        std::cout << dis(gen) << ' ';
    std::cout << '\n';
}
//正太分佈
#include <iostream>
#include <iomanip>
#include <string>
#include <map>
#include <random>
#include <cmath>
int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
 
    // values near the mean are the most likely
    // standard deviation affects the dispersion of generated values from the mean
    std::normal_distribution<> d(5,2);
 
    std::map<int, int> hist;
    for(int n=0; n<10000; ++n) {
        ++hist[std::round(d(gen))];
    }
    for(auto p : hist) {
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                  << p.first << ' ' << std::string(p.second/200, '*') << '\n';
    }
}
相關文章
相關標籤/搜索