我很难理解为什么这段代码(尝试<random>
在 C++11 中使用新标头)正确地生成随机数,[0, 2**62 - 1]
但不是[0, 2**63 - 1]
or [0, 2**64 - 1]
。
#include <iostream>
#include <stdint.h>
#include <random>
#include <functional>
#include <ctime>
static std::mt19937 engine; // Mersenne twister MT19937
void print_n_random_bits (unsigned int n);
int main (void) {
engine.seed(time(0));
print_n_random_bits(64);
print_n_random_bits(63);
print_n_random_bits(62);
return 0;
}
void print_n_random_bits (unsigned int n)
{
uintmax_t max;
if (n == 8 * sizeof(uintmax_t)) {
max = 0;
} else {
max = 1;
max <<= n;
}
--max;
std::uniform_int_distribution<uintmax_t> distribution(0, max);
std::cout << n << " bits, max: " << max << std::endl;
std::cout << distribution(engine) << std::endl;
}
现在,更多的挖掘揭示了std::mt19937_64
,它具有正确的行为,但是谁能向我解释为什么适用于 62 位数字的东西不适用于 64 位数字?
编辑:对不起,我什至没有指定问题。问题是对于 63 位和 64 位最大值,输出始终是 range 中的一个数字[0, 2**32 - 1]
,例如:
% ./rand
64 bits, max: 18446744073709551615
1803260654
63 bits, max: 9223372036854775807
3178301365
62 bits, max: 4611686018427387903
2943926730538475327
% ./rand
64 bits, max: 18446744073709551615
1525658116
63 bits, max: 9223372036854775807
2093351390
62 bits, max: 4611686018427387903
1513326512211312260
% ./rand
64 bits, max: 18446744073709551615
884934896
63 bits, max: 9223372036854775807
683284805
62 bits, max: 4611686018427387903
2333288494897435595
编辑 2:我正在使用clang++
( Apple clang version 2.1 (tags/Apple/clang-163.7.1)
) 和“libc++”。由于我的版本不c++0x
支持,因此我无法使用 GCC 轻松测试上述内容。