除了是个垃圾程序员外,我的行话也不达标。我会尽力解释我自己。
我已经使用 randomlib 实现了 Merssene twister 随机数生成器.
诚然,我不太熟悉 Visual 8 C++ 的随机数生成器的工作原理,但我发现我可以在 main()
中为它播种一次 srand(time(NULL))
和我可以在其他类(class)中安全地使用 rand()
。
我拥有的 Merssene twister 需要创建一个对象,然后为该对象播种。
#include <RandomLib/Random.hpp>
RandomLib::Random r; // create random number object
r.Reseed(); // seed with a "unique" seed
float d = r.FloatN(); // a random in [0,1] rounded to the nearest double
如果我想在类中生成一个随机数,我该怎么做,而不必每次都定义一个对象。我只是担心,如果我使用计算机时钟,每次运行都会使用相同的种子(每秒仅更改一次)。
我的解释对吗?
提前致谢
最佳答案
Random 对象本质上是您需要保留的状态信息。您可以使用所有常规技术:可以将其作为全局变量或将其作为参数传递。如果一个特定的类需要随机数,你可以保留一个 Random
对象作为类成员为该类提供随机性。
C++ <random>
库的相似之处在于它需要构建一个对象作为随机性/RNG 状态的来源。这是一个很好的设计,因为它允许程序控制对状态的访问,例如,保证多线程的良好行为。 C++ <random>
库甚至包括梅森扭曲算法。
这是一个示例,显示将 RNG 状态保存为类成员(使用 std::mt19937
而不是 Random
)
#include <random> // for mt19937
#include <algorithm> // for std::shuffle
#include <vector>
struct Deck {
std::vector<Cards> m_cards;
std::mt19937 eng; // save RNG state as class member so we don't have to keep creating one
void shuffle() {
std::shuffle(std::begin(m_cards), std::end(m_cards), eng);
}
};
int main() {
Deck d;
d.shuffle();
d.shuffle(); // this reuses the RNG state as it was at the end of the first shuffle, no reseeding
}
关于c++ - 正确播种随机数生成器(Mersenne twister)c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13166058/