升压C ++ - 生成0和1之间的随机的实数 [英] Boost C++ - generating a random real number between 0 and 1
问题描述
我一直在阅读了Boost C ++文档,并试图找出如何产生0和1之间的随机实数,使用该库的 uniform_01
部分。有没有人有什么建议?
I've been reading the Boost C++ documentation and trying to figure out how to generate a random real number between 0 and 1, using the uniform_01
part of the library. Does anyone have any suggestions?
根据建议,我用这code,但它会产生相同的随机值每一次。
Based on suggestions, I'm using this code, but it generates the same random value every time.
double random01(mt19937 & generator)
{
uniform_01<mt19937> dist(generator);
return dist();
}
int main()
{
mt19937 generator(time(0));
for (int i = 0; i < 10; i++) {
cout << random01(generator) << endl;
}
return 0;
}
很抱歉,如果我不清晰;这个问题不解决,我的答案或任何其他。它的每一次仍然产生相同的随机值。
Sorry if I wasn't clear; this question isn't solved, by my answer or any other. It's still generating the same random value each time.
推荐答案
有一些疑难杂症在这code:
There are a few 'gotcha's in this code:
- 的
random01()
功能并不需要到发电机的引用,而是复制发电机。所以,如果你调用该函数使用相同的发电机多次 - 它会一遍又一遍产生相同的值 - 的
静态
uniform_01
在random01()
只被初始化的第一次调用random01,所以如果是曾经与不同的生成调用,它不会使用它,而是使用第一发生器,它甚至可能已被破坏的参考,因为!
- The
random01()
function does not take a reference to the generator, but rather a copy of the generator. So if you call the function multiple times with the same generator - it will produce the same value over and over again! - The
static
uniform_01
inrandom01()
only gets initialized on the first call to random01, so if it is ever called with a different generator, it will not use it, but rather use a reference to the first generator, which may even have been destroyed, since!
正确的将类似以下内容(注意&功放;在参数列表
,用于传递按引用,而缺乏的静态
:
Correct would be something like following (note the &
in the arguments list, for pass-by-reference, and the lack of static
:
double random01(mt19937 & generator)
{
uniform_01<mt19937> dist(generator);
return dist();
}
这篇关于升压C ++ - 生成0和1之间的随机的实数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!