简体   繁体   English

更改 c++ 中的种子或随机数生成器

[英]Changing the seed or a random number generator in c++

I have this program where I use the mersenne twister generator like so:我有这个程序,我像这样使用 mersenne twister 生成器:

#include <iostream>
#include <random>
using namespace std;

unsigned seed = 131353;
mt19937 generator(seed);
normal_distribution<real> distribution(0.0, 1.0);

int main() {
    cout << distribution(generator);
}

for me it's convenient to declare this generator outside of main so that it is a global variable, so that I don't have to keep passing it as an argument in the functions I have;对我来说,在 main 之外声明这个生成器很方便,这样它就是一个全局变量,这样我就不必在我拥有的函数中一直将它作为参数传递;

but I want to read the seed from a file, which as far as I am aware can only be done inside the main() function.但我想从文件中读取种子,据我所知,这只能在 main() function 内部完成。

Is it possible to declare the generator as a global variable and set the seed inside main()?是否可以将生成器声明为全局变量并在 main() 中设置种子?

Thanks in advance提前致谢

I tried reading the seed from a file outside main function, without success so far我尝试从主 function 之外的文件中读取种子,但到目前为止没有成功

which as far as I am aware can only be done inside the main() function.据我所知,这只能在 main() function 内部完成。

Not really.并不真地。 You can seed it directly when initializing it.可以在初始化的时候直接播种。 Example:例子:

#include <fstream>
#include <iostream>
#include <random>

// call a function/lambda to fetch the seed from the file:
std::mt19937 generator([]{
                           std::mt19937::result_type seed{};
                           if(std::ifstream fs("file_with_seed"); fs)
                               fs >> seed;
                           return seed;
                       }());

std::normal_distribution<double> distribution(0.0, 1.0);

int main() {
    std::cout << distribution(generator);
}

If you want to seed it in main , you can use the seed member function.如果你main中播种,可以使用seed成员 function。

#include <fstream>
#include <iostream>
#include <random>

std::mt19937 generator;
std::normal_distribution<double> distribution(0.0, 1.0);

int main() {
    generator.seed([]{
                       std::mt19937::result_type seed{};
                       if(std::ifstream fs("file_with_seed"); fs)
                           fs >> seed;
                       return seed;
                   }());

    std::cout << distribution(generator);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM