欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++随机数引擎

程序员文章站 2023-04-05 22:32:12
C++的随机数引擎有以下几个要点需要注意: 1、随机数发生器使用同一种子会生成相同序列的随机数序列 2、为了让程序每次运行都会生成不同的随机结果,我们可以使用 time(0) 产生一个随机数种子 3、我们必须传递引擎本身给分布对象,因为有些分布可能需要调用引擎多次才能得出结果 以下是几种随机分布: ......

c++的随机数引擎有以下几个要点需要注意:

   1、随机数发生器使用同一种子会生成相同序列的随机数序列

  2、为了让程序每次运行都会生成不同的随机结果,我们可以使用 time(0) 产生一个随机数种子

  3、我们必须传递引擎本身给分布对象,因为有些分布可能需要调用引擎多次才能得出结果

 

以下是几种随机分布:

  1、均匀分布:(1) 产生随机整数:uniform_int_distribution<[type]> u[(range)]

           (2) 产生随机小数:uniform_real_distribution<[type]> u[(range)]

   2正态分布:normal_distribution<[type]> n(e, d)

   3伯努利分布:bernoulli_distribution b[(概率)],返回 bool 值,且返回 true 的概率为常数,默认为 0.5 

 

注:这些随机分布都包含在头文件 random 里面

 

 

#include <iostream>
#include <cstdlib> 
#include <ctime>
#include <cmath>
#include <random>
#include <vector>

using namespace std;

int main()
{
    static default_random_engine e;
//    返回该引擎能生成的最小及最大值 
    cout<<"min: "<<e.min()<<ends<<"max: "<<e.max()<<endl;
    
//    time 返回以秒计的时间 
    e.seed(time(0));
    
    static uniform_int_distribution<unsigned> u(0, 9);
    cout<<"生成[0,9]的3个随机整数为:"; 
    for (size_t i = 0; i < 3; ++i)
        cout<<u(e)<<ends;
    cout<<endl;
    
    /*
        u.min() 和 u.max() 返回 u(e) 能生成的最小和最大值
        u.reset() 重建 u 的状态,使随后对 u 的使用不依赖于 u 已经生成的值 
    */
        
    static uniform_real_distribution<double> r(0, 1);
    cout<<"生成[0, 1]的3个随机小数为:";
    for (size_t i = 0; i < 3; ++i)
        cout<<r(e)<<ends;
    cout<<endl;
    
    static normal_distribution<> n(4, 1.5);
    cout<<"正态分布个数统计:"<<endl;
    vector<unsigned> vals(9);
    for (size_t i = 0; i != 100; ++i){
//        cmath 的 lround 函数把值舍入到最接近的整数 
        unsigned v = lround(n(e));
        if (v < vals.size())
            ++vals[v];
    }
    for (size_t i = 0; i < vals.size(); ++i)
        cout<<i<<":\t"<<vals[i]<<endl;
        
//     返回 true 的概率为 0 
    static bernoulli_distribution b(0);
    for (size_t i = 0; i < 3; ++i)
        cout<<boolalpha<<b(e)<<noboolalpha<<ends;
    cout<<endl;
    
    system("pause");
        
    return 0;
}