Uniformity of random numbers taken modulo N

前端 未结 4 1233
北海茫月
北海茫月 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:03

    That depends on:

    • The value of RAND_MAX
    • Your value of N

    Let us assume your RAND_MAX is 2^32. If N is rather small (let's say 2) then the bias is 1 / 2^31 -- or too small to notice.

    But if N is quite a bit larger, say 2^20, then the bias is 1 / 2^12, or about 1 in 4096. A lot bigger, but still pretty small.

提交回复
热议问题