C++11 随机数

 1 /*************************************************************************
 2   > File Name   : test_random_device.cc
 3   > Author      : sanghai
 4   > Mail        : sanghai.window@gmail.com
 5   > Created Time: 2017年08月12日 星期六 02时11分04秒
 6  ************************************************************************/
 7 
 8 // 标准把随机数抽象成(随机数引擎)和(分布两部分).引擎用来产生随机数,分布产生特定分布的随机数(比如平均分布,正太分布等).
 9 
10 #include <iostream>
11 #include <random>
12 using namespace std;
13 
14 // 随机数生成器(linux 实现是读/dev/urandom设备), 通常仅用做种子(假如硬件殇池耗尽,randm_device会下滑)
15 // 根据计算机硬件的殇,生成一个随机数, 一般作为种子初始化随机数引擎
16 void test_random_device()
17 {
18     random_device rd;
19     for (int i = 0; i < 100; ++i)
20         cout << rd() << endl;
21 }
22 
23 // 预定义随机数生成器,即随机数生成算法
24 // 随即种子一定,相同算法产生出的随机数列亦相同, 默认种子为5489u
25 // 按照一定算法,生成一个内部维护一定长度不可重复序列的随机引擎(随机数生产器)对象(即随机数)
26 void test_mt19937()
27 {
28     random_device rd;
29     // ***************** 梅森螺旋算法(), 号称最好的伪随机数生成算法 默认seed:5489u*****************
30     // 即 mt为梅森螺旋算法生成的一个数列
31     // 32-bit numbers with a state size of 19937 bits
32     mt19937 mt(rd());
33 
34     // ***************** 采用线性同余算法, 速度快, 默认seed:1u*****************
35     // 即 mr为线性同余算法生成的一个数列
36     // result_type: uint_fast32_t(long int)
37     minstd_rand0 mr(rd());
38 
39     // result_type: unsinged int
40     default_random_engine e(rd());
41     // ***************** 采用线性同余算法, 速度快, 默认seed:1u*****************
42 }
43 
44 // 随机数分布, 从随机数生成器对象(mt19937 minstd_rand0)中选取一定范围的数据分布
45 // 从随机数中得到一定分布(统计概率密度)的结果
46 void test_random_distribution()
47 {
48     // 产生随机整数值i,均匀分布的,即,根据离散概率函数分布在闭区间[a, b]
49     random_device rd;
50     mt19937 gen(rd());
51     uniform_int_distribution<> disInt(1, 6);
52 
53     for (int i = 0; i < 10; ++i)
54         cout << disInt(gen) << ',' << endl;
55 
56     uniform_real_distribution<> disReal(1, 2);
57 
58     // 产生随机浮点值i,均匀地分布在区间[a, b)
59     for (int i = 0; i < 10; ++i)
60         cout << disReal(gen) << ',';
61     cout << endl;
62 }
63 
64 int main(void)
65 {
66     test_random_device();
67     return 0;
68 }
test_random_device
#include <iostream>
#include <vector>
#include <string>
#include <random>

// size 不大于 1000个
std::vector<unsigned> randVec(int size=10, int low=0, int high=1000)
{
    std::cout << "个数不大于1000个" << std::endl;
    // 种子
    std::random_device r;
    // 梅森螺旋算法数据生成器
    static std::mt19937 mt(r());
    // [low, high]
    static std::uniform_int_distribution<> dis(low, high);

    std::vector<unsigned> ret;
    for (int i = 0; i < size; ++i)
        ret.push_back(dis(mt));

    return ret;
}

// std::vector<unsigned> instance(randVec());
myRandDataEngin

参考:

cppreference

cplusplus

gitbooks

原文地址:https://www.cnblogs.com/sanghai/p/7348621.html