std::mersenne_twister_engine and random number generation

前端 未结 4 1523
野趣味
野趣味 2021-01-20 16:49

What is the distribution (uniform, poisson, normal, etc.) that is generated if I did the below? The output appears to indicate a uniform distribution. But then, why do we ne

4条回答
  •  隐瞒了意图╮
    2021-01-20 17:01

    Because while generator() is an uniform distribution over [generator.min(), generator.max()], generator() % n is not a uniform distribution over [0, n) (unless generator.max() is an exact multiple of n, assuming generator.min() == 0).

    Let's take an example: min() == 0, max() == 65'535 and n == 7.

    gen() will give numbers in the range [0, 65'535] and in this range there are:

    • 9'363 numbers such that gen() % 7 == 0
    • 9'363 numbers such that gen() % 7 == 1
    • 9'362 numbers such that gen() % 7 == 2
    • 9'362 numbers such that gen() % 7 == 3
    • 9'362 numbers such that gen() % 7 == 4
    • 9'362 numbers such that gen() % 7 == 5
    • 9'362 numbers such that gen() % 7 == 6

    If you are wondering where did I get these numbers think of it like this: 65'534 is an exact multiple of 7 (65'534 = 7 * 9'362). This means that in [0, 65'533] there are exactly 9'362 numbers who map to each of the {0, 1, 2, 3, 4, 5, 6} by doing gen() % 7. This leaves 65'534 who maps to 0 and 65'535 who maps to 1

    So you see there is a bias towards [0, 1] than to [2, 6], i.e.

    • 0 and 1 have a slightly higher chance (9'363 / 65'536 ≈ 14.28680419921875 %)‬ of appearing than
    • 2, 3, 4, 5 and 6 (9'362 / 65'536 ≈ 14.2852783203125‬ %).

    std::uniformn_distribution doesn't have this problem and uses some mathematical woodo with possibly getting more random numbers from the generator to achieve a truly uniform distribution.

提交回复
热议问题