Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skewing java random number generation toward a certain number

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

like image 972
convergedtarkus Avatar asked May 02 '11 03:05

convergedtarkus


People also ask

How do you generate a random number between 1 to 10 in Java?

For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);


1 Answers

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
like image 54
user1417684 Avatar answered Oct 05 '22 02:10

user1417684