生成2 ^ 30的随机数

时间:2012-10-19 19:21:35

标签: java c++ c

我想生成0到2 ^ 10范围内的2^30个随机数。我听说rand()函数不适合这么多数字。有没有其他方法可以生成它几乎相等的分布?

6 个答案:

答案 0 :(得分:3)

C ++ <random>库是一个很好的选择,有很多PRNG引擎和分发选择。

#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 << ' ';
    }
}

此外,random_device本身就是一个引擎,根据实现情况,它可以提供对非确定性或加密RNG的访问:

std::random_device eng;
std::cout << dist(eng) << '\n';

例如,在libc ++中,它默认使用/ dev / urandom,在OS X上使用Yarrow加密RNG算法。

答案 1 :(得分:2)

在Java中,您可以使用Random,它在2 ^ 48个值之后重复。

Random rand = new Random();

for(int i = 0; i < (1<<30); i++) {
    int n = rand.nextInt(1 << 10);

}

答案 2 :(得分:1)

  

g_random_int()返回在[0..2 ^ 32-1]范围内均匀分布的随机guint32。

#include <glib.h>

int
main(void)
{
     g_print("%d\n", g_random_int());
   return 0;
}

使用gcc:

gcc -o rand rand.c `pkg-config --cflags --libs glib-2.0`

编辑:

直接从/ dev / random读取(不太便携),像往常一样编译:

#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:检查错误。

答案 3 :(得分:1)

这是一篇旧的Usenet帖子,里面有许多有趣的RNG - 都非常容易实现。

http://www.cse.yorku.ca/~oz/marsaglia-rng.html

它们可能与Mersenne twister不太匹配,但我已经很好地利用了它们中的一些,它们肯定优于一些默认的rand()实现。它们通过随机性的DIEHARD测试,并且包括的最大周期发生器具有> 2 ^ 7700并且只需要几行来实现。

答案 4 :(得分:0)

Mark A. Overton于2011年5月24日在Dr. Dobbs上发表了一篇关于相当简单但高质量RING的文章

答案 5 :(得分:0)

增加随机性和周期的简单方法:

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

}
相关问题