2012-10-19 213 views
5

我想在0到2^10的范围内生成2^30随机数。我听说rand()函数不适合这么多的数字。是否有任何其他方式来产生它几乎相等的分布?生成随机数2^30

+4

调查C++ 11的''标题。 – chris

+1

而在C++ 03中,Boost.Random(其中''来自)。 – GManNickG

+1

生成均匀分布的大型随机数不存在问题吗? – andre

回答

1

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

#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读/随机(便携性较差),编译照例:

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

+0

rand.c是我的文件,我存储了这段代码吗?(抱歉,我对编译器知之甚少) – john

+0

@jhon 如果你只是想要0到2^32之间的随机数然后从/ dev/random读取它会给你随机性本身:P在你的shell中试试这个: 'od -An -N4 -tu/dev/random | tr -d''' 重定向到文件 'od -An -N4 -tu/dev/random | tr -d''> file.txt' 但是;如果您将上面的代码复制并粘贴到一个名为rand.c的文件中,则只需输入上述命令即可编译它。注意代码有一个要求,你需要在你的系统中安装glib。 当然,如果你不使用Linux,这些都不会起作用。 – yeyo

+0

好的感谢与我能够做的shell命令。但是当我用上面的命令为文件rand.c做它时,它坚持用符号>>。 – john

0

马克·奥弗顿5月24日对相当简单但高品质的RNG一个很好的文章Dr. Dobbs,2011

2

在Java中,你可以使用随机其不经过2^48的值重复。

Random rand = new Random(); 

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

} 
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算法。

+0

其错误提示为:'mt19937_64'不是'std'的成员 – john

+0

您使用的编译器/库和版本是什么?它可能还没有实现。您也可以尝试'std :: mt19937'或其他[预定义的随机数生成器](http://en.cppreference.com/w/cpp/numeric/random)。 – bames53

+0

它显示gcc版本4.6.3 – john

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

} 
1

这里有一个旧的Usenet帖子,里面有很多有趣的RNG - 所有这些都很容易实现。

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

他们可能不完全匹配的梅森难题,但我已经取得了良好的使用其中几个,他们肯定优于某些默认兰特()实现。他们通过随机性的DIEHARD测试,并且包含的​​最大周期发生器具有> 2^7700的周期,并且不超过几行执行。

Ken