Generating a random bit - lack of randomness in C rand()

后端 未结 4 1695
礼貌的吻别
礼貌的吻别 2020-11-30 14:13

I am using rand() to generate either 0 or 1 (rand() % 2). I am seeding it using the current time (srand(time(NULL))).

After mu

4条回答
  •  失恋的感觉
    2020-11-30 14:34

    Instead of using rand()%2, try rand()>(RAND_MAX/2). You can only assume rand() to be uniform on the interval [0, RAND_MAX].

    Edit: This was suggested by Shahbaz in the comments, which I only noticed after I posted this answer.

    Edit: ArjunShankar called me out on my previous wording: "rand() is only specified to be uniform on the interval [0, RAND_MAX]"

    From the C99 standard:

    The rand function computes a sequence of pseudo-random integers in the range 0 to RAND_MAX.

    Technically, uniformity (or equidistributed) is not specified, but is the de-facto standard used for implementations of commonly used PRNG's (e.g. Mersenne Twister). This is to allow a programmer to easily create a custom PRNG with a non-uniform distribution. Without this property, a programmer is forced to implement a custom PRNG from scratch.

提交回复
热议问题