I want to generate 2^30
random numbers in the range of 0 to 2^10. I heard that rand()
function is not suitable for this many numbers.Is there any another way to generate it with nearly equal distribution?
The C++ <random>
library is an excellent option, with many choices of PRNG engine and distribution.
#include <random>
#include <cstdint>
#include <iostream>
int main() {
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937_64 eng(seed);
std::uniform_int_distribution<> dist(0, 1<<10);
for (std::uint32_t i = 0; i< (1<<30); ++i) {
int value = dist(eng);
std::cout << value << ' ';
}
}
Also, random_device is itself an engine which may, depending on the implementation, provide access to a non-deterministic or cryptographic RNG:
std::random_device eng;
std::cout << dist(eng) << '\n';
For example in libc++ it uses /dev/urandom by default, which on OS X uses the Yarrow cryptographic RNG algorithm.
In Java you can use Random which does repeat after 2^48 values.
Random rand = new Random();
for(int i = 0; i < (1<<30); i++) {
int n = rand.nextInt(1 << 10);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With