Java: random integer with non-uniform distribution

前端 未结 11 1622
终归单人心
终归单人心 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:37

    The Cumulative Distribution Function is x^2 for a triangular distribution [0,1] with mode (highest weighted probability) of 1, as shown here.

    Therefore, all we need to do to transform a uniform distribution (such as Java's Random::nextDouble) into a convenient triangular distribution weighted towards 1 is: simply take the square root Math.sqrt(rand.nextDouble()), which can then multiplied by any desired range.

    For your example:

    int a = 1; // lower bound, inclusive
    int b = k; // upper bound, exclusive
    double weightedRand = Math.sqrt(rand.nextDouble()); // use triangular distribution
    weightedRand = 1.0 - weightedRand; // invert the distribution (greater density at bottom)
    int result = (int) Math.floor((b-a) * weightedRand);
    result += a; // offset by lower bound
    if(result >= b) result = a; // handle the edge case 
    

提交回复
热议问题