[C++11]C++11による乱数ジェネレータ

6028 ワード

C++11は多くの特性をもたらし、randomはその1つである.
1. random_device
標準ライブラリは、非確定乱数生成装置を提供する.Linuxの実装では、読み取り/dev/urandomデバイスである.Windowsの実装はrand_s、ここで強く非難します.
  random_デバイスは、min()からmax()の間の数値を返すための()オペレータを提供する.Linux(Unix LikeまたはUnix)の場合、いずれもこれを用いる高品質の乱数を生成することができ、真の乱数と理解できる.
#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 engine
標準は乱数を乱数エンジンと分布の2つの部分に抽象化する.エンジンは乱数を生成するために用いる、分布は特定の分布の乱数(例えば平均分布、正太分布など)を生成する.
標準は3つの一般的なエンジンを提供します:linear_congruential_engine,mersenne_twister_engineとsubtract_with_carry_engine.1つ目は線形同余アルゴリズムであり、2つ目はメイソン回転アルゴリズムであり、3つ目はキャリー付き線形同余アルゴリズムである.1つ目は最もよく使われており、速度も非常に速い.第2の種は最良の擬似乱数生成器と称される.3つ目は使ったことがありません....
乱数エンジンは1つの整形パラメータをシードとして受け入れ、提供しないとデフォルト値が使用される.おすすめはrandom_deviceは種子として乱数を生成する.(windowsの下でどのように整頓するのが好きで、誰がwindowsのrandom_deviceがrand_sを呼び出すのです)
#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 distributions
標準は様々な分布を提供していますが、平均分布、正太分布など、よく使われているものは少ないです.使いやすい
//    

#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 << '
'; }
//    

#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, '*') << '
'; } }

 
参照先:
1. http://en.cppreference.com/w/cpp/numeric/random
2.Windowsの高品質乱数生成器、CryptGenRandom API、http://www.cnblogs.com/egmkang/archive/2011/03/05/1971586.htmlを参照