Is there a function for obtaining uniformly distributed pseudo-random integers in some specified range? I could write my own function using rand
, but this seems like a common enough situation that there's probably something in the STL for it.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
Boost provides many tools for random number generation. For uniform distributions you have this one:
http://www.boost.org/doc/libs/1_49_0/doc/html/boost/random/uniform_real_distribution.html
EDIT: updated to include the new C++11 implementation. For the case of integers, here you have the reference:
http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
A simple example would be:
To generate pseudo-random numbers in C++, a very good option is using the Mersenne twister pseudo-random number generator engine:
std::mt19937
from the<random>
header.We can think of this engine as a black-box that spits out high-quality random bits.
Then, these random bits can be shaped in some integers output using a distribution; in particular, to get uniformly distributed pseudo-random numbers, a
std::uniform_int_distribution
can be used.Note that the engine object must be initialized with a seed.
std::random_device
can be used for that purpose.So, this process can be summarized in three logical steps:
std::random_device
, to get a non-deterministic seed for the Mersenne twister engine.std::mt19937
engine, to get high-quality pseudo-random bits.std::uniform_int_distribution
to shape these random bits in uniformly-distributed integers.Compilable C++ code follows:
For more details on generating pseudo-random numbers in C++ (including reasons why
rand()
is not good), see this video by Stephan T. Lavavej (from Going Native 2013):To generate one or specified number of random variables with uniform distribution on integer domain using
std::generate_n
andboost
: