mathematics behind modulo behavor

蓝咒 提交于 2019-12-02 11:44:07

In essence, you're doing:

(rand() & 7) % 6

Let's assume that rand() is uniformly distributed on [0; RAND_MAX], and that RAND_MAX+1 is a power of two. It is clear that rand() & 7 can evaluate to 0, 1, ..., 7, and that the outcomes are equiprobable.

Now let's look at what happens when you take the result modulo 6.

  • 0 and 6 map to 0;
  • 1 and 7 map to 1;
  • 2 maps to 2;
  • 3 maps to 3;
  • 4 maps to 4;
  • 5 maps to 5.

This explains why you get twice as many zeroes and ones as you get the other numbers.

The same thing is happening in the second case. However, the value of the "extra" numbers is much smaller, making their contribution indistinguishable from noise.

To summarize, if you have an integer uniformly distributed on [0; M-1], and you take it modulo N, the result will be biased towards zero unless M is divisible by N.

rand() (or some other PRNG) produces values in the interval [0 .. RAND_MAX]. You want to map these to the interval [0 .. N-1] using the remainder operator.

Write

(RAND_MAX+1) = q*N + r

with 0 <= r < N.

Then for each value in the interval [0 .. N-1] there are

  • q+1 values of rand() that are mapped to that value if the value is smaller than r
  • q values of rand() that are mapped to it if the value is >= r.

Now, if q is small, the relative difference between q and q+1 is large, but if q is large - 2^32 / 6, for example - the difference cannot easily be measured.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!