Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Random number of 2^30

Tags:

java

c++

c

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?

like image 894
john Avatar asked Oct 19 '12 19:10

john


2 Answers

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.

like image 160
bames53 Avatar answered Sep 28 '22 10:09

bames53


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);

}
like image 39
Peter Lawrey Avatar answered Sep 28 '22 12:09

Peter Lawrey