有没有一个函数生成一个随机int数在C?或者我必须使用第三方库?


当前回答

有人很好地解释了为什么使用rand()在给定范围内生成均匀分布的随机数是一个坏主意,我决定看看输出到底有多倾斜。我的测试案例是公平掷骰子。下面是C代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[])
{
    int i;
    int dice[6];

    for (i = 0; i < 6; i++) 
      dice[i] = 0;
    srand(time(NULL));

    const int TOTAL = 10000000;
    for (i = 0; i < TOTAL; i++)
      dice[(rand() % 6)] += 1;

    double pers = 0.0, tpers = 0.0;
    for (i = 0; i < 6; i++) {
      pers = (dice[i] * 100.0) / TOTAL;
      printf("\t%1d  %5.2f%%\n", dice[i], pers);
      tpers += pers;
    }
    printf("\ttotal:  %6.2f%%\n", tpers);
}

这是它的输出:

 $ gcc -o t3 t3.c
 $ ./t3 
        1666598  16.67%     
        1668630  16.69%
        1667682  16.68%
        1666049  16.66%
        1665948  16.66%
        1665093  16.65%
        total:  100.00%
 $ ./t3     
        1667634  16.68%
        1665914  16.66%
        1665542  16.66%
        1667828  16.68%
        1663649  16.64%
        1669433  16.69%
        total:  100.00%

我不知道你需要你的随机数有多统一,但上面的看起来足够统一,满足大多数需求。

编辑:用比time(NULL)更好的东西初始化PRNG是个好主意。

其他回答

#include <stdio.h>
#include <dos.h>

int random(int range);

int main(void)
{
    printf("%d", random(10));
    return 0;
}

int random(int range)
{
    struct time t;
    int r;

    gettime(&t);
    r = t.ti_sec % range;
    return r;
}

在现代的x86_64 cpu上,您可以通过_rdrand64_step()使用硬件随机数生成器。

示例代码:

#include <immintrin.h>

uint64_t randVal;
if(!_rdrand64_step(&randVal)) {
  // Report an error here: random number generation has failed!
}
// If no error occured, randVal contains a random 64-bit number

对于Linux C应用程序:

这是我根据上面的答案重新编写的代码,它遵循我的C代码实践并返回任意大小的随机缓冲区(具有适当的返回代码等)。确保在程序开始时调用urandom_open()一次。

int gUrandomFd = -1;

int urandom_open(void)
{
    if (gUrandomFd == -1) {
        gUrandomFd = open("/dev/urandom", O_RDONLY);
    }

    if (gUrandomFd == -1) {
        fprintf(stderr, "Error opening /dev/urandom: errno [%d], strerrer [%s]\n",
                  errno, strerror(errno));
        return -1;
    } else {
        return 0;
    }
}


void urandom_close(void)
{
    close(gUrandomFd);
    gUrandomFd = -1;
}


//
// This link essentially validates the merits of /dev/urandom:
// http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
//
int getRandomBuffer(uint8_t *buf, int size)
{
    int ret = 0; // Return value

    if (gUrandomFd == -1) {
        fprintf(stderr, "Urandom (/dev/urandom) file not open\n");
        return -1;
    }

    ret = read(gUrandomFd, buf, size);

    if (ret != size) {
        fprintf(stderr, "Only read [%d] bytes, expected [%d]\n",
                 ret, size);
        return -1;
    } else {
        return 0;
    }
}

如果您需要128个安全随机位,符合RFC 1750的解决方案是读取已知可以生成可用熵位的硬件源(例如旋转磁盘)。更好的是,好的实现应该使用混合函数组合多个源,并最终通过重新映射或删除输出来消除输出分布的倾斜。

如果你需要更多的比特,你需要做的就是从128个安全随机比特的序列开始,并将其拉伸到所需的长度,将其映射到人类可读的文本等等。

如果你想在C中生成一个安全的随机数,我将遵循这里的源代码:

https://wiki.sei.cmu.edu/confluence/display/c/MSC30-C.+Do+not+use+the+rand%28%29+function+for+generating+pseudorandom+numbers

注意,对于Windows bbcryptgenrandom是使用的,而不是CryptGenRandom,在过去的20年里已经变得不安全。您可以亲自确认BCryptGenRandom符合RFC 1750。

For POSIX-compliant operating systems, e.g. Ubuntu (a flavor of Linux), you can simply read from /dev/urandom or /dev/random, which is a file-like interface to a device that generates bits of entropy by combining multiple sources in an RFC 1750 compliant fashion. You can read a desired number of bytes from these "files" with read or fread just like you would any other file, but note that reads from /dev/random will block until a enough new bits of entropy are available, whereas /dev/urandom will not, which can be a security issue. You can get around that by checking the size of the available entropy pool, either my reading from entropy_avail, or by using ioctl.

尽管这里所有人都建议使用rand(),但除非迫不得已,否则您不会想要使用rand() !rand()生成的随机数通常非常糟糕。引用Linux手册页:

Linux C库中的rand()和srand()版本使用与random(3)和srandom(3)相同的随机数生成器,因此低阶位应该与高阶位一样随机。但是,在旧的rand()实现上,以及在不同系统上的当前实现上,低阶位比高阶位随机得多。当需要良好的随机性时,不要在旨在可移植的应用程序中使用此函数。(请使用random(3)。)

关于可移植性,random()也由POSIX标准定义了很长一段时间。rand()更老,它已经出现在第一个POSIX.1规范(IEEE Std 1003.1-1988)中,而random()首次出现在POSIX.1-2001 (IEEE Std 1003.1-2001)中,然而当前的POSIX标准已经是POSIX.1-2008 (IEEE Std 1003.1-2008),仅在一年前收到了更新(IEEE Std 1003.1-2008, 2016版)。所以我认为random()是非常可移植的。

POSIX.1-2001还引入了lrand48()和mrand48()函数,参见这里:

此函数族应使用线性同余算法和48位整数算术生成伪随机数。

一个很好的伪随机源是arc4random()函数,它在许多系统上都可用。不是任何官方标准的一部分,在1997年左右出现在BSD中,但你可以在Linux和macOS/iOS等系统上找到它。