Java: random integer with non-uniform distribution

前端 未结 11 1639
终归单人心
终归单人心 2020-12-13 12:55

How can I create a random integer n in Java, between 1 and k with a "linear descending distribution", i.e. 1 is

11条回答
  •  星月不相逢
    2020-12-13 13:35

    There are many ways to generate a random integer with a custom distribution (also known as a discrete distribution). The choice depends on many things, including the number of integers to choose from, the shape of the distribution, and whether the distribution will change over time.

    One of the simplest ways to choose an integer with a custom weight function f(x) is the rejection sampling method. The following assumes that the highest possible value of f is max. The time complexity for rejection sampling is constant on average, but depends greatly on the shape of the distribution and has a worst case of running forever. To choose an integer in [1, k] using rejection sampling:

    1. Choose a uniform random integer i in [1, k].
    2. With probability f(i)/max, return i. Otherwise, go to step 1.

    Other algorithms have an average sampling time that doesn't depend so greatly on the distribution (usually either constant or logarithmic), but often require you to precalculate the weights in a setup step and store them in a data structure. Some of them are also economical in terms of the number of random bits they use on average. These algorithms include the alias method, the Fast Loaded Dice Roller, the Knuth–Yao algorithm, the MVN data structure, and more. See my section "A Note on Weighted Choice Algorithms" for a survey.

提交回复
热议问题