Java: random integer with non-uniform distribution

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

    Something like this....

    class DiscreteDistribution
    {
        // cumulative distribution
        final private double[] cdf;
        final private int k;
    
        public DiscreteDistribution(Function pdf, int k)
        {
            this.k = k;
            this.cdf = new double[k];
            double S = 0;
            for (int i = 0; i < k; ++i)
            {
                double p = pdf.apply(i+1);         
                S += p;
                this.cdf[i] = S;
            }
            for (int i = 0; i < k; ++i)
            {
                this.cdf[i] /= S;
            }
        }
        /**
         * transform a cumulative distribution between 0 (inclusive) and 1 (exclusive)
         * to an integer between 1 and k.
         */
        public int transform(double q)
        {
            // exercise for the reader:
            // binary search on cdf for the lowest index i where q < cdf[i]
            // return this number + 1 (to get into a 1-based index.
            // If q >= 1, return k.
        }
    }
    

提交回复
热议问题