Unsparing
Unsparing

Reputation: 7653

Java: Generate N random numbers which mean is going to be M

I didn't manage to find such function in Math.random or Util.random. For example I give a mean of 2 and generate N random numbers which when I average them the average to be the number (in this case 2) which I gave to the function.

public static int[] randomNumbersWithGivenMean(int average)
{
  ...
}

Upvotes: 1

Views: 1298

Answers (2)

Nicholas Betsworth
Nicholas Betsworth

Reputation: 1793

In general, if you generate a list of random numbers in the range of 1..N, the mean value of the list items will be N / 2. The larger your list, the more likely this is to hold true.

public static int[] getRandomList(int average, int listSize) {
    Random rand = new Random();
    int[] list = new int[listSize];

    for(int i = 0; i < listSize; i++) {
        list[i] = rand.nextInt(average * 2) + 1;
    }

    return list;
}

You did not mention the range of numbers you wished to generate, so I have assumed 1..N will suffice. If you wish to change this you must ensure that you generate the numbers evenly over average.

Upvotes: 3

Fox
Fox

Reputation: 2368

Are you looking for Gaussian distribution random numbers?

Please see JavaDoc for Class Random

There is a method called nextGaussian(), which as stated in the doc:

Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

You have to then alter the result to fit your desired standard deviation (by multiplication) and mean (by addition).

The more times you call the nextGaussian(), the better (number mean closer to the desired mean) will be.

Upvotes: 3

Related Questions