您好,登錄后才能下訂單哦!
c庫偽隨機數發生器
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;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。