Uniformity of random numbers taken modulo N

前端 未结 4 1224
北海茫月
北海茫月 2020-12-01 18:48

One common way of choosing a random number in [0, n) is to take the result of rand() modulo n: rand() % n. However, even if the r

4条回答
  •  情歌与酒
    2020-12-01 19:04

    One approach you can do is the following:

    Knowing the value of N, you make R_MAX = ((RAND_MAX + 1) / N) * N; for uniformity.

    So you can do your custom rand() function:

    int custom_rand(int mod) {
        int x = rand();
        const int R_MAX = ((RAND_MAX + 1) / mod) * mod;    
    
        while (x > R_MAX) { // discard the result if it is bigger
            x = rand();
        }
    
        return (x % mod);
    }
    

提交回复
热议问题