Reputation: 99
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?
Upvotes: 5
Views: 405
Reputation: 842
Here's an old Usenet post with a number of interesting RNGs - all very easily implemented.
http://www.cse.yorku.ca/~oz/marsaglia-rng.html
They may not quite match the Mersenne twister, but I have made good use of several of them and they are certainly superior to some of the default rand() implementations. They pass the DIEHARD tests of randomness and the largest period generator included has period > 2^7700 and takes no more than a couple of lines to implement.
Upvotes: 1
Reputation: 88225
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.
Upvotes: 3
Reputation: 3009
g_random_int() return a random guint32 equally distributed over the range [0..2^32-1].
#include <glib.h>
int
main(void)
{
g_print("%d\n", g_random_int());
return 0;
}
with gcc:
gcc -o rand rand.c `pkg-config --cflags --libs glib-2.0`
EDIT:
reading directly from /dev/random (less portable), compile as usual:
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
int
main(void)
{
int fd;
unsigned int number;
fd = open("/dev/random", O_RDONLY);
read(fd, &number, sizeof(number));
printf("%u\n", number);
close(fd);
return 0;
}
PS: check for errors.
Upvotes: 1
Reputation: 76016
A simple way to increment the randomness and period:
public class Random2 {
private static int LEN = 64;
private final int[] buf = new int[LEN];
private Random r;
private final int maxInt = 1 << 10;
public Random2() {
r = new Random();
for (int i = 0; i < LEN; i++)
buf[i] = r.nextInt(maxInt);
}
public int nextInt() {
int i = r.nextInt(LEN);
int x = buf[i];
buf[i] = r.nextInt(maxInt);
return x;
}
}
Upvotes: 0
Reputation: 533870
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);
}
Upvotes: 2
Reputation: 41220
Mark A. Overton had a nice article on fairly simple but high quality RNGs on Dr. Dobbs on May 24, 2011
Upvotes: 0