Skewing java random number generation toward a certain number

前端 未结 2 2048
陌清茗
陌清茗 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 13:46

    Try http://download.oracle.com/javase/6/docs/api/java/util/Random.html#nextGaussian()

    Math.max(1, Math.min(100, (int) 75 + Random.nextGaussian() * stddev)))
    

    Pick a stddev like 10 and play around until you get the distribution you want. There are going to be slightly more at 1 and 100 though than at 2 or 99. If you want to change the rate at which it drops off, you can raise the gaussian to a power.

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题