I'm having difficulty understanding why this code, an attempt to use the new
header in C++11, is correctly generating random numbers in [0, 2**62 - 1]
but not [0, 2**63 - 1]
or [0, 2**64 - 1]
.
#include
#include
#include
#include
#include
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 distribution(0, max);
std::cout << n << " bits, max: " << max << std::endl;
std::cout << distribution(engine) << std::endl;
}
Nu, een beetje meer graven onthult std: mt19937_64
, wat het juiste gedrag heeft, maar kan iemand mij uitleggen waarom iets dat werkt voor een 62-bits getal niet werkt voor een 64 bit-nummer?
Edit: Sorry, I didn't even specify the problem. The problem is that for 63 and 64 bit max values, the output is consistently a number in the range [0, 2**32 - 1]
, e.g.:
% ./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
Edit 2: I'm using clang++
(Apple clang version 2.1 (tags/Apple/clang-163.7.1)
) and "libc++". I can't easily test the above with GCC as my version doesn't have c++0x
support.