std :: mersenne_twister_engine和随机数生成 [英] std::mersenne_twister_engine and random number generation
问题描述
如果执行以下操作,将产生什么分布(均匀分布,泊松分布,正态分布等)?输出似乎表明分布均匀.但是,为什么我们需要std::uniform_int_distribution
?
What is the distribution (uniform, poisson, normal, etc.) that is generated if I did the below? The output appears to indicate a uniform distribution. But then, why do we need std::uniform_int_distribution
?
int main()
{
std::mt19937_64 generator(134);
std::map<int, int> freq;
const int size = 100000;
for (int i = 0; i < size; ++i) {
int r = generator() % size;
freq[r]++;
}
for (auto f : freq) {
std::cout << std::string(f.second, '*') << std::endl;
}
return 0;
}
谢谢!
推荐答案
因为generator()
是[generator.min(), generator.max()]
上的均匀分布,所以generator() % n
不是[0, n)
上的均匀分布(除非generator.max()
是假设generator.min()== 0)n
的精确倍数.
Because while generator()
is an uniform distribution over [generator.min(), generator.max()]
, generator() % n
is not a uniform distribution over [0, n)
(unless generator.max()
is an exact multiple of n
, assuming generator.min() == 0).
让我们举个例子:min() == 0
,max() == 65'535
和n == 7
.
Let's take an example: min() == 0
, max() == 65'535
and n == 7
.
gen()
将给出范围为[0, 65'535]
的数字,并且在以下范围内:
gen()
will give numbers in the range [0, 65'535]
and in this range there are:
-
9'363
编号,例如gen() % 7 == 0
-
9'363
编号,例如gen() % 7 == 1
-
9'362
编号,例如gen() % 7 == 2
-
9'362
编号,例如gen() % 7 == 3
-
9'362
编号,例如gen() % 7 == 4
-
9'362
编号,例如gen() % 7 == 5
-
9'362
编号,例如gen() % 7 == 6
9'363
numbers such thatgen() % 7 == 0
9'363
numbers such thatgen() % 7 == 1
9'362
numbers such thatgen() % 7 == 2
9'362
numbers such thatgen() % 7 == 3
9'362
numbers such thatgen() % 7 == 4
9'362
numbers such thatgen() % 7 == 5
9'362
numbers such thatgen() % 7 == 6
如果您想知道这些数字是从哪里得到的,请像这样:65'534
是7
(65'534 = 7 * 9'362
)的精确倍数.这意味着在[0, 65'533]
中,确切地是9'362
个数字,它们通过执行gen() % 7
映射到每个{0, 1, 2, 3, 4, 5, 6}
.这样,将65'534
映射到0
,将65'535
映射到1
If you are wondering where did I get these numbers think of it like this: 65'534
is an exact multiple of 7
(65'534 = 7 * 9'362
). This means that in [0, 65'533]
there are exactly 9'362
numbers who map to each of the {0, 1, 2, 3, 4, 5, 6}
by doing gen() % 7
. This leaves 65'534
who maps to 0
and 65'535
who maps to 1
因此,您看到对[0, 1]
的偏爱要比对[2, 6]
的偏爱,即
So you see there is a bias towards [0, 1]
than to [2, 6]
, i.e.
-
0
和1
出现的几率(9'363 / 65'536 ≈ 14.28680419921875 %
)比 -
2
,3
,4
,5
和6
(9'362 / 65'536 ≈ 14.2852783203125 %
).
0
and1
have a slightly higher chance (9'363 / 65'536 ≈ 14.28680419921875 %
) of appearing than2
,3
,4
,5
and6
(9'362 / 65'536 ≈ 14.2852783203125 %
).
std::uniformn_distribution
不存在此问题,并使用了一些数学上的可可性,可能会从生成器中获取更多随机数以实现真正的均匀分布.
std::uniformn_distribution
doesn't have this problem and uses some mathematical woodo with possibly getting more random numbers from the generator to achieve a truly uniform distribution.
这篇关于std :: mersenne_twister_engine和随机数生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!