与std :: chrono :: high_resolution_clock在班级内播种STD :: MT19937的
What is the proper way of seeding std::mt19937 with std::chrono::high_resolution_clock inside a class?
首先,大家好!这是我在这里的第一个问题,所以我希望我不会搞砸。在这里写作之前,我谷歌搜索了很多。我是编码,C 的新手,我自己学习。
考虑到我被告知我只播种任何随机发动机是一个好习惯(我可能错了(班级,由std::chrono::high_resolution_clock::now().time_since_epoch().count()
从Chrono Standard库中播种?
我想使用该计时值,因为它的变化很快,并且会产生令人毛骨悚然的数字。我从未考虑过std::random_device
,因为我认为这有点阴暗。我可能再次错了。
编辑:我在大多数情况下代码并在Android手机上使用C4Droid IDE学习,因为我没有太多空闲时间坐在适当的计算机上,所以我认为这就是为什么我认为std::random_device
并不是真正可靠的。
我在知道什么是课之前就成功完成了,但是我现在正在学习课程并进行了很多反复试验(将static_cast到处都是static_cast,尝试const,static等,因为代码总是给出错误(完成此操作:
class Deck
{
private:
std::array<Card, 52> m_card;
const int m_seed {static_cast<int>(std::chrono::high_resolution_clock::now().time_since_epoch().count())};
std::mt19937 m_rng {m_seed};
int rng(int min, int max)
{
std::uniform_int_distribution<> rng{min, max};
return rng(m_rng);
}
void swapCard(Card &a, Card &b)
{
Card temp {a};
a = b;
b = temp;
}
public:
Deck()
{
int index{0};
for (int iii {0}; iii < Card::CS_MAX; ++iii)
{
for (int jjj {0}; jjj < Card::CR_MAX; ++jjj)
{
m_card[index] = Card(static_cast<Card::CardSuit>(iii), static_cast<Card::CardRank>(jjj));
++index;
}
}
}
void printDeck() const
{
for (int iii {0}; iii < 52; ++iii)
{
m_card[iii].printCard();
if (((iii + 1) % 13 == 0) && iii != 0)
std::cout << 'n';
else
std::cout << ' ';
}
}
void shuffleDeck(int xTimes = 1)
{
for (int iii {0}; iii < xTimes; ++iii)
{
for (int jjj {0}; jjj < 52; ++jjj)
{
swapCard(m_card[jjj], m_card[rng(0, 51)]);
}
}
}
};
这有效,但我不知道这是否是正确的方法。另外,有人告诉我,永远可以使静态变化的变量可以在班级的所有对象之间共享,但是我不能使m_seed static ...
我很确定有一种更有效的方法。你们可以帮忙吗?
我被告知,只有一旦播种任何随机发动机
才是一个好习惯
听起来像是合理的建议。我想补充一点,您最好每个线程完全具有一个发电机,因为实例化和播种需要时间,并且标准发电机不安全。
我认为
std::random_device
不是真正可靠的
应该能够通过其entropy()
函数告诉您它是否是通过其CC_6函数。零熵表示其熵池是空的,甚至不存在。在后一种情况下,您会从中获得伪随机数。
正确的方法是什么...
通过阅读评论和其他一些提示中的链接,这就是我到目前为止收集的:
- 创建一个种子序列类,该类别创建与生成器所需的种子值一样多。如果
std::random_device
中的熵为零,请将其尽可能地与其他来源结合在一起。我认为Hashedtime_point
样本花了一段时间可以与rd()
结合使用,因为在输入值中1个更改位应理想地更改Hashed值的一半位。 - 创建一个共享生成器,该发电机会自动实例化和从(新(线程要求时进行播种,因为因为发电机不是线程安全的。
- 创建从生成器继承的分布模板,以便一个线程中的所有分布共享同一生成器。
- 不要实例化分布超出必要。如果您经常使用相同的发行版,请保留。
这是代码中注释的尝试:
#include <iostream>
#include <chrono>
#include <climits>
#include <functional>
#include <iterator>
#include <random>
#include <thread>
#include <type_traits>
#include <utility>
//----------------------------------------------------------------------------------
// sexmex - A hash function kindly borrowed from Pelle Evensens yet to be published
// work: http://mostlymangling.blogspot.com/
//
// g++ 8.3.1: std::hash<Integer-type> lets the value through as-is (identity)
// so I'll use this to create proper hash values instead.
template<typename Out = size_t, typename In>
inline std::enable_if_t<sizeof(In) * CHAR_BIT <= 64 &&
std::numeric_limits<Out>::is_integer &&
std::numeric_limits<In>::is_integer,
Out>
sexmex(In v) {
uint64_t v2 = static_cast<uint64_t>(v); // cast away signedness
v2 ^= (v2 >> 20) ^ (v2 >> 37) ^ (v2 >> 51);
v2 *= 0xA54FF53A5F1D36F1ULL; // Fractional part of sqrt(7)
v2 ^= (v2 >> 20) ^ (v2 >> 37) ^ (v2 >> 51);
v2 *= 0x510E527FADE682D1ULL; // Fractional part of sqrt(11)
v2 ^= (v2 >> 20) ^ (v2 >> 37) ^ (v2 >> 51);
// Discard the high bits if Out is < 64 bits. This particular hash function
// has not shown any weaknesses in the lower bits in any widely known test
// suites yet.
return static_cast<Out>(v2);
}
//----------------------------------------------------------------------------------
class seeder {
public:
using result_type = std::uint_least32_t;
// function called by the generator on construction to fill its internal state
template<class RandomIt>
void generate(RandomIt Begin, RandomIt End) const noexcept {
using seed_t = std::remove_reference_t<decltype(*Begin)>;
std::random_device rd{};
if(rd.entropy() == 0.) { // check entropy
// zero entropy, add some
constexpr auto min = std::chrono::high_resolution_clock::duration::min();
std::vector<seed_t> food_for_generator(
static_cast<size_t>(std::distance(Begin, End)));
for(int stiring = 0; stiring < 10; ++stiring) {
for(auto& food : food_for_generator) {
// sleep a little to ensure a new clock count each iteration
std::this_thread::sleep_for(min);
std::this_thread::sleep_for(min);
auto cc = std::chrono::high_resolution_clock::now()
.time_since_epoch()
.count();
food ^= sexmex<seed_t>(cc);
food ^= sexmex<seed_t>(rd());
}
stir_buffer(food_for_generator);
}
// seed the generator
for(auto f = food_for_generator.begin(); Begin != End; ++f, ++Begin)
*Begin = *f;
} else {
// we got entropy, use random_device almost as-is but make sure
// values from rd() becomes seed_t's number of bits and unbiased
// via sexmex.
//
// seed the generator
for(; Begin != End; ++Begin) *Begin = sexmex<seed_t>(rd());
}
}
private:
template<typename SeedType>
inline void stir_buffer(std::vector<SeedType>& buf) const noexcept {
for(size_t i = 0; i < buf.size() * 2; ++i) {
buf[i % buf.size()] += static_cast<SeedType>(
sexmex(buf[(i + buf.size() - 1) % buf.size()] + i));
}
}
};
//----------------------------------------------------------------------------------
struct shared_generator {
// we want one instance shared between all instances of uniform_dist per thread
static thread_local seeder ss;
static thread_local std::mt19937 generator;
};
thread_local seeder shared_generator::ss{};
thread_local std::mt19937 shared_generator::generator(ss);
//----------------------------------------------------------------------------------
// a distribution template for uniform distributions, both int and real
template<typename T>
class uniform_dist : shared_generator {
public:
uniform_dist(T low, T high) : distribution(low, high) {}
// make instances callable
inline T operator()() { return distribution(generator); }
private:
template<class D>
using dist_t =
std::conditional_t<std::is_integral_v<D>, std::uniform_int_distribution<D>,
std::uniform_real_distribution<D>>;
dist_t<T> distribution;
};
//----------------------------------------------------------------------------------
void thread_func() {
uniform_dist<int> something(0, 10);
for(int i = 0; i < 10; ++i) std::cout << something() << "n";
}
int main() {
// all distributions sharing the same generator:
uniform_dist<size_t> card_picker(0, 51);
uniform_dist<int16_t> other(-32768, 32767);
uniform_dist<float> fd(-1000.f, 1000.f);
uniform_dist<double> dd(-1., 1.);
for(int i = 0; i < 10; ++i) std::cout << card_picker() << "n";
std::cout << "--n";
for(int i = 0; i < 10; ++i) std::cout << other() << "n";
std::cout << "--n";
for(int i = 0; i < 10; ++i) std::cout << fd() << "n";
std::cout << "--n";
for(int i = 0; i < 10; ++i) std::cout << dd() << "n";
// in the thread function, a new generator will be created and seeded.
std::thread t(thread_func);
t.join();
}
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::mt19937从字符串中返回一个随机单词
- <random>在实践中应该实际使用哪个随机数引擎? std::mt19937?
- std::mt19937 in Rcpp
- test1.cpp:9:77:错误:对"(const std::normal_distribution) <double>(std::mt19937&)"的调用不匹配
- 我应该使用std::seed_seq来种子std::mt19937吗
- 只有 std::mt19937 的实例在 c++11 中重复值
- 与std :: chrono :: high_resolution_clock在班级内播种STD :: MT19937的
- 我应该使用std :: default_random_engine还是应该使用std :: mt19937
- std::mt19937 不返回随机数
- 如何使用 std::mt19937 避免相同的随机结果
- Is std::mt19937_64 faster than std::mt19937?
- 是否遵循均匀分布::random_device 和 std::mt19937