I am learning parallel computing at the moment, and for a exercise I need random number generators in parallel. But I do not seem to be able to use a RNG in subroutines, so that they return different numbers. The following code is the simplest test I made, while figuring out how to do this. For each iteration it returns the same number, but I do not know why. Would you please explain what I do not understand.
#include <iostream>
#include <random>
void morerandom(double& num, double seednum)
{
std::mt19937 mt;
mt.seed(seednum);
std::uniform_real_distribution<double> ureal_d(0.,1.);
num = ureal_d(mt);
}
int main()
{
std::vector<double> nums = {0.1, 0.4, 0.3, 0.3, 0.1};
std::vector<double> results(5,0.);
for (unsigned k=0; k<5; k++)
{
morerandom(results[k], nums[k]);
std::cout << results[k] << std::endl;
}
return 0;
}
seed
的参数应该是int
或其他整数类型 ,由于从double
转换为int
,因此总是使用0
作为种子。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.