Skewing java random number generation toward a certain number

前端 未结 2 2073
陌清茗
陌清茗 2021-01-04 13:29

How, in Java, would you generate a random number but make that random number skewed toward a specific number. For example, I want to generate a number between 1 and 100 inc

2条回答
  •  心在旅途
    2021-01-04 14:01

    Question is a bit old, but if anyone wants to do this without the special case handling, you can use a function like this:

        final static public Random RANDOM = new Random(System.currentTimeMillis());
    
        static public double nextSkewedBoundedDouble(double min, double max, double skew, double bias) {
            double range = max - min;
            double mid = min + range / 2.0;
            double unitGaussian = RANDOM.nextGaussian();
            double biasFactor = Math.exp(bias);
            double retval = mid+(range*(biasFactor/(biasFactor+Math.exp(-unitGaussian/skew))-0.5));
            return retval;
        }
    

    The parameters do the following:

    • min - the minimum skewed value possible
    • max - the maximum skewed value possible
    • skew - the degree to which the values cluster around the mode of the distribution; higher values mean tighter clustering
    • bias - the tendency of the mode to approach the min, max or midpoint value; positive values bias toward max, negative values toward min

提交回复
热议问题