c/c++产生随机数
2016-03-16 22:40
513 查看
c库伪随机数发生器
rand
srand
大多时候用时间产生随机发生器的seed
c++11 引入的伪随机数发生器.随机数抽象成随机数引擎和分布两部分.引擎用来产生随机数,分布产生特定分布的随机数
常用的就是线性均匀分布
uniform_int_distribution
uniform_real_distribution
还有一些其他发生器,如 伯努里分布、泊松分布、正态分布
rand
srand
大多时候用时间产生随机发生器的seed
int GetRandomNum(int min, int max,int seed) { //srand((unsigned)time(NULL)); //生成seed srand(seed); return( rand() % (max - min) + min); }
c++11 引入的伪随机数发生器.随机数抽象成随机数引擎和分布两部分.引擎用来产生随机数,分布产生特定分布的随机数
常用的就是线性均匀分布
uniform_int_distribution
uniform_real_distribution
std::random_device rd;//来产生一个随机数当作种子 std::uniform_int_distribution<int> uni_dist(0, 9999999); //指定范围的随机数发生器 std::cout << uni_dist(rd) << std::endl;
还有一些其他发生器,如 伯努里分布、泊松分布、正态分布
// ConsoleApplication4.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <random> #include <memory> #include <iostream> using namespace std; class Random { public: const static unsigned int maxRand = std::random_device::max(); static Random& getInstance() { static Random instance; return instance; } unsigned int getInteger() noexcept { return (*dist)(rd); } unsigned int GetMTEngineInteger() noexcept { return (*mtEngine)(); } uint64_t GetMTEngine64Integer() noexcept { return (*mtEngine64)(); } unsigned int GetRand0Integer() noexcept { return (*rand0Engine)(); } auto GetRanlux48Integer() noexcept ->decltype(auto) { return (*ranlux48Engine)(); } private: Random() noexcept { mtEngine = std::make_shared<std::mt19937>(rd()); mtEngine64 = std::make_shared<std::mt19937_64>(rd()); dist = std::make_shared<std::uniform_int_distribution< unsigned int >>(std::uniform_int_distribution< unsigned int >(0, maxRand)); rand0Engine = make_shared<std::minstd_rand0>(rd()); ranlux48Engine = make_shared<std::ranlux48>(rd()); } std::random_device rd; std::shared_ptr<std::mt19937> mtEngine; //32-bit Mersenne Twister by Matsumoto and Nishimura, 1998 std::shared_ptr<std::mt19937_64> mtEngine64; //64-bit Mersenne Twister by Matsumoto and Nishimura, 2000(马特赛特旋转演算法) std::shared_ptr<std::minstd_rand0> rand0Engine; std::shared_ptr<std::ranlux48> ranlux48Engine; std::shared_ptr<std::uniform_int_distribution< unsigned int > > dist; }; int main() { cout << Random::getInstance().GetMTEngineInteger() << endl; cout << Random::getInstance().GetMTEngine64Integer() << endl; cout << Random::getInstance().GetRand0Integer() << endl; cout << Random::getInstance().GetRanlux48Integer() << endl; cout << Random::getInstance().getInteger() << endl; return 0; }
相关文章推荐
- 几何原本查询程序2.5
- c/C++中后缀obj/o lib/a dll/so bin文件意义
- C++一些数字的求法
- 23种设计模式:现代C++实现 V2.0
- C/C++中const关键字详解
- 面向对象(二)
- 二叉搜索树的一种构造方法
- c++ assert() 使用方法
- C++ STL--stack/queue 的使用方法
- C++:单向链表实现
- 用C++实现bitmap
- C++拷贝构造函数详解
- c++实现双向单链表
- 常见算法:C语言求最小公倍数和最大公约数三种算法
- 在VC++中启用内存泄露检测
- C++ 排序函数 sort(),qsort()的用法
- c++实现单向单链表及常见面试题
- C++的多态性
- 适配器模式(C++)
- 第五届蓝桥杯大赛个人赛省赛(软件类)真题(C语言A组)