C++ 在main中调用的函数中使用std::uniform_real_分布
我试图在main中调用的函数中使用std::uniform_real_分布 我主要按照以下方式为发电机播种:C++ 在main中调用的函数中使用std::uniform_real_分布,c++,random,C++,Random,我试图在main中调用的函数中使用std::uniform_real_分布 我主要按照以下方式为发电机播种: unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator (seed); std::uniform_real_distribution<double> distribution(0.0,1.0);
unsigned seed =
std::chrono::system_clock::now().time_since_epoch().count();
std::default_random_engine generator (seed);
std::uniform_real_distribution<double> distribution(0.0,1.0);
当我需要一个随机数的时候
问题是我还需要数百万美元
函数中的随机数
想象一下我在main中调用的函数:
int main(){
void function(){
number = distribution(generator)
}
return 0;
}
如何做到这一点?如何访问函数中的随机数生成器
非常感谢 你可以把它变成一个函数。我建议使用std::mt19937作为随机数生成器,并至少使用std::random_设备对其进行种子设定 大概是这样的:
inline
double random_number(double min, double max)
{
// use thread_local to make this function thread safe
thread_local static std::mt19937 mt{std::random_device{}()};
thread_local static std::uniform_real_distribution<double> dist;
using pick = std::uniform_real_distribution<double>::param_type;
return dist(mt, pick(min, max));
}
int main()
{
for(int i = 0; i < 10; ++i)
std::cout << i << ": " << random_number(2.5, 3.9) << '\n';
}
你把它传递给函数?不要把时间当作种子,那根本不是随机的。不要使用std::default\u random\u引擎,这通常是不好的。在我的问题中,你可以找到一个合适的方法来播种一个好的RNG。谢谢!在读了你的评论后,我做了类似的事情。它起作用了!
inline
double random_number(double min, double max)
{
// use thread_local to make this function thread safe
thread_local static std::mt19937 mt{std::random_device{}()};
thread_local static std::uniform_real_distribution<double> dist;
using pick = std::uniform_real_distribution<double>::param_type;
return dist(mt, pick(min, max));
}
int main()
{
for(int i = 0; i < 10; ++i)
std::cout << i << ": " << random_number(2.5, 3.9) << '\n';
}
1: 3.73887
2: 3.68129
3: 3.41809
4: 2.64881
5: 2.93931
6: 3.15629
7: 2.76597
8: 3.55753
9: 2.90251