Skewing java random number generation toward a cer

2019-02-12 20:10发布

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 inclusive, but I want that number skewed toward say, 75. But I still want the possibility of getting other numbers in the range, but I want more of a change of getting numbers close to say 75 as opposed to just getting random numbers all across the range. Thanks

2条回答
淡お忘
2楼-- · 2019-02-12 20:29

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.

查看更多
做个烂人
3楼-- · 2019-02-12 20:29

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
查看更多
登录 后发表回答