Search code examples
c++uniform-distribution

Uniform int32 Distribution


Is there any way to get uniform int32_t distribution without a warning? I use this uniform_int_distribution<int32_t> in my code but I get a warning:

54988961.cpp: In function ‘int main()’:
54988961.cpp:6:64: warning: overflow in conversion from ‘double’ to ‘int’ changes value from ‘1.0e+10’ to ‘2147483647’ [-Woverflow]
     std::uniform_int_distribution<std::int32_t> unif(1,std::pow(10,10));
                                                        ~~~~~~~~^~~~~~~

This is exactly my code:

#include <cmath>
#include <cstdint>
#include <random>

int main() {
    std::uniform_int_distribution<std::int32_t> unif(1,std::pow(10,10));
}

Solution

  • pow(10, 10)
    

    This is 10000000000, an int32 can only hold 2147483647 (2^31 - 1). You should use int64_t if you want to be able to store your pow(10, 10).

    Since your min value is 1 you could also just go for its unsigned counterpart.