首先,大家好!这是我在这里的第一个问题,所以我希望我没有搞砸。在写这篇文章之前我用谷歌搜索了很多。我是编程新手,也是c++的新手,我正在自学。
考虑到我被告知这是一个很好的实践(我在这里可能是错的),在一个类中使用随机标准库中的std::mt19937
的正确/最佳/更有效的方法是什么?
我想使用计时值,因为它变化非常快,并且会生成一个可怕的数字。我从来没有考虑过std::random_device
,因为我认为它有点可疑。我可能又错了。
编辑:大多数时候我在我的安卓手机上使用C4Droid集成开发环境编程和学习,因为我没有太多的空闲时间坐在一台合适的电脑上,所以这就是为什么我认为std::random_device
不是真正可靠的原因。
在我知道类是什么之前,我已经成功地做到了这一点,但我现在正在学习类,并做了很多尝试和错误(将static_casts放在任何地方,尝试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设为静态变量。
我非常确定有一种更有效的方法来做到这一点。你们能帮上忙吗?
发布于 2019-05-23 07:13:13
我被告知这是一个很好的实践,任何随机引擎只需播种一次
这听起来像是个不错的建议。我想补充的是,你最好每个线程只有一个生成器,因为实例化和播种它需要时间,并且标准生成器不是线程安全的。
我认为
std::random_device
并不是很可靠
它应该能够通过它的entropy()
函数告诉你是否是。零熵意味着它的熵池是空的,或者根本不存在。在后一种情况下,您将从中获得伪随机数。
什么是正确的方式...
通过阅读评论中的链接和其他一些技巧,这是我到目前为止收集的:
std::random_device
中的熵为零,请尽可能将其与其他来源相结合。我认为散列的value.time_point
中的一半位。共享生成器在从(新的)线程请求时自动实例化和播种,因为生成器不是线程安全的。下面是在代码中添加注释的尝试:
#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();
}
https://stackoverflow.com/questions/56242943
复制相似问题