C++ TR1 置随机数种子

1、

#include <stdlib.h>
#include <random>
#include <iostream>
using namespace std;
void main()
{
    std::tr1::mt19937 eng;  // a core engine class:Mersenne Twister generator

    std::cout<<"产生正态分布的10个随机数:"<<endl;
    std::tr1::normal_distribution<double> dist;
    for (int i=0; i<10; i++)
    {
        std::cout<<dist(eng)<<endl;
    }

    std::cout<<"\n产生均匀分布的在1到52之间的五个整数随机数:"<<endl;
    std::tr1::uniform_int<int> unif(1, 52); 
    for (int i=0; i<5; i++)
    {
        std::cout<<unif(eng)<<endl;
    }
    system("pause");
}

 

上述代码每次运行时生成的随机数序列固定不变:

2、

 1 #include <random>
 2 #include <iostream>
 3 #include <time.h>
 4 using namespace std;
 5 void main()
 6 {
 7     std::tr1::mt19937 eng;  // a core engine class:Mersenne Twister generator
 8     eng.seed((unsigned int)time(NULL)); // reseed base engine 设置种子用#include <time.h>, 不能用#include <time>
 9 
10     std::cout<<"产生正态分布的10个随机数:"<<endl;
11     std::tr1::normal_distribution<double> dist;
12     for (int i=0; i<10; i++)
13     {
14         std::cout<<dist(eng)<<endl;
15     }
16 
17     std::cout<<"\n产生均匀分布的在1到52之间的五个整数随机数:"<<endl;
18     std::tr1::uniform_int<int> unif(1, 52); 
19     for (int i=0; i<5; i++)
20     {
21         std::cout<<unif(eng)<<endl;
22     }
23     system("pause");
24 }

 

posted on 2013-07-16 14:07  whl-hl  阅读(585)  评论(0编辑  收藏  举报

导航