How to generate a random int in C?

2018-12-31 05:23发布

Is there a function to generate a random int number in C? Or will I have to use a third party library?

标签: c random
24条回答
临风纵饮
2楼-- · 2018-12-31 05:38

I had a serious issue with pseudo random number generator in my recent application: I repeatidly called my C program via a pyhton script and I was using as seed the following code:

srand(time(NULL))

However, since:

  • rand will generate the same pseudo random sequence give the same seed in srand (see man srand);
  • As already stated, time function changes only second from second: if your application is run multiple times within the same second, time will return the same value each time.

My program generated the same sequence of numbers. You can do 3 things to solve this problem:

  1. mix time output with some other information changing on runs (in my application, the output name):

    srand(time(NULL) | getHashOfString(outputName))
    

    I used djb2 as my hash function.

  2. Increase time resolution. On my platform, clock_gettime was available, so I use it:

    #include<time.h>
    struct timespec nanos;
    clock_gettime(CLOCK_MONOTONIC, &nanos)
    srand(nanos.tv_nsec);
    
  3. Use both methods together:

    #include<time.h>
    struct timespec nanos;
    clock_gettime(CLOCK_MONOTONIC, &nanos)
    srand(nanos.tv_nsec | getHashOfString(outputName));
    

Option 3 ensures you (as far as i know) the best seed randomity, but it may create a difference only on very fast application. In my opinion option 2 is a safe bet.

查看更多
若你有天会懂
3楼-- · 2018-12-31 05:41

The standard C function is rand(). It's good enough to deal cards for solitaire, but it's awful. Many implementations of rand() cycle through a short list of numbers, and the low bits have shorter cycles. The way that some programs call rand() is awful, and calculating a good seed to pass to srand() is hard.

The best way to generate random numbers in C is to use a third-party library like OpenSSL. For example,

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/rand.h>

/* Random integer in [0, limit) */
unsigned int random_uint(unsigned int limit) {
    union {
        unsigned int i;
        unsigned char c[sizeof(unsigned int)];
    } u;

    do {
        if (!RAND_bytes(u.c, sizeof(u.c))) {
            fprintf(stderr, "Can't get random bytes!\n");
            exit(1);
        }
    } while (u.i < (-limit % limit)); /* u.i < (2**size % limit) */
    return u.i % limit;
}

/* Random double in [0.0, 1.0) */
double random_double() {
    union {
        uint64_t i;
        unsigned char c[sizeof(uint64_t)];
    } u;

    if (!RAND_bytes(u.c, sizeof(u.c))) {
        fprintf(stderr, "Can't get random bytes!\n");
        exit(1);
    }
    /* 53 bits / 2**53 */
    return (u.i >> 11) * (1.0/9007199254740992.0);
}

int main() {
    printf("Dice: %d\n", (int)(random_uint(6) + 1));
    printf("Double: %f\n", random_double());
    return 0;
}

Why so much code? Other languages like Java and Ruby have functions for random integers or floats. OpenSSL only gives random bytes, so I try to mimic how Java or Ruby would transform them into integers or floats.

For integers, we want to avoid modulo bias. Suppose that we got some random 4 digit integers from rand() % 10000, but rand() can only return 0 to 32767 (as it does in Microsoft Windows). Each number from 0 to 2767 would appear more often than each number from 2768 to 9999. To remove the bias, we can retry rand() while the value is below 2768, because the 30000 values from 2768 to 32767 map uniformly onto the 10000 values from 0 to 9999.

For floats, we want 53 random bits, because a double holds 53 bits of precision (assuming it's an IEEE double). If we use more than 53 bits, we get rounding bias. Some programmers write code like rand() / (double)RAND_MAX, but rand() might return only 31 bits, or only 15 bits in Windows.

OpenSSL's RAND_bytes() seeds itself, perhaps by reading /dev/urandom in Linux. If we need many random numbers, it would be too slow to read them all from /dev/urandom, because they must be copied from the kernel. It is faster to allow OpenSSL to generate more random numbers from a seed.

More about random numbers:

查看更多
君临天下
4楼-- · 2018-12-31 05:41

This is hopefully a bit more random than just using srand(time(NULL)).

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

int main(int argc, char **argv)
{
    srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL));
    srand(rand());

    for (int i = 0; i < 10; i++)
        printf("%d\n", rand());
}
查看更多
其实,你不懂
5楼-- · 2018-12-31 05:42

Have a look at ISAAC (Indirection, Shift, Accumulate, Add, and Count). Its uniformly distributed and has an average cycle length of 2^8295.

查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 05:42
#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;
}
查看更多
临风纵饮
7楼-- · 2018-12-31 05:43

This is a good way to get a random number between two numbers of your choice.

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

    #define randnum(min, max) \
        ((rand() % (int)(((max) + 1) - (min))) + (min))

int main()
{
    srand(time(NULL));

    printf("%d\n", randnum(1, 70));
}

Output the first time: 39

Output the second time: 61

Output the third time: 65

You can change the values after randnum to whatever numbers you choose, and it will generate a random number for you between those two numbers.

查看更多
登录 后发表回答