What is the best way to generate random numbers?
相关问题
- 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
If you're talking standard C++ library pre C++11, rand and srand are your random number generators. There are ways to get more accuracy out of these functions than using modulus with integer arithmetic. You could use doubles, for example, if high speed isn't a concern and round the results to int.
As for custom libraries, if you really want good random distribution and speed, google Mersenne Twister. There are also options in boost.
With C++11 you have
<random>
. http://en.cppreference.com/w/cpp/numeric/randomBoost.Random is an excellent library for producing pseudorandom numbers (or truly random, if the platform supports it).
You should use
<random>
:Pre C++11 you could find this either in TR1 (
<tr1/random>
,std::tr1::mt19937
etc.), or in Boost.random, with essentially the same interface (though there are minor differences).If and only if:
you are not looking for "perfect uniformity" or
you have no C++11 support and not even TR1 (thus you don't have another choice)
then you might consider using the following C-style solution, which (for the sake of the reputation of this community ~ see rand() Considered Harmful) is written in strike-through font:
Here's the simple C-style function that generates random number from the interval from
min
tomax
, inclusive. Those numbers seem to be very close to being uniformly distributed.and don't forget to call
srand
before you use it:output:
14253 14481 14210 14029 14289 14503 14235
Also have a look at:
Generate a random number within range?
Generate random numbers uniformly over an entire range
and find some time and watch at least first 11 minutes of aforementioned video
Otherwise:
use
<random>
just like it was pointed out by Kerrek SB already.My 'random' library provide a high convenient wrapper around C++11 random classes. You can do almost all things with a simple 'get' method.
Examples:
And even more things ! Check out the github page:
https://github.com/effolkronium/random