I need to generate random numbers, but from as wide a range as possible (64 bit at least). I don't care if the distribution is perfect, so std::rand()
would work, but it only returns an int
. I understand that c++11 has some random number generating capability that can give any size number, but is very complex to use. Can someone post a simple example of how to use it as simply as possible to get the described functionality (64 bit or more random numbers) in as simple a way as possible (like std::rand()
)?
相关问题
- 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
We could easily wrap a random number generator engine into srand/rand-like methods like this:
(Like
srand
andrand
, this implementation does not care about thread-safety.)Well the wrapper functions are so trivial that you could just use the engine directly.
This is how to use the C++11 random number generation for this purpose (adjusted from http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution):
Instead of
unsigned long long
, you could usestd::uintmax_t
fromcstdint
to get the largest possible integer range (without using an actual big-integer library).Not C++11, but easy enough
((unsigned long long)rand() << 32) + rand()
Here we generate two parts of int64 as int32'sAs
JasonD
pointed out, it assumes thatrand()
generate 32bit integer. It' spossible to xorrand() << x
,rand() << (2*x)
,rand() << (3*x)
, etc, wherex
<= bit's in generate byrand()
number`. It should be OK too.