Generating a set of uniformly distributed random numbers
I have a list of objects N
.
I would like to insert X
mock objects that are randomly placed between real objects N
between (0, N).
So, I tried the following code.
int[] dummyIndexes = new int[X];
int randomStep = N/X * 2; // *2 because the Mean is N/X/2
Random random = new Random();
int randIdx = 0;
for (int i=0; i < X; i++)
{
randIdx += random.nextInt(randomStep);
dummyIndexes[i] = randIdx;
}
This works well, although I don't get a good distribution right up to the end of the domain N
.
What's the best way to do this?
+3
source to share
2 answers
This will do the trick (but note that it will be a newer place in N, the largest value will be N-1)
int[] dummyIndexes = new int[X];
int randomStep = N/X;
Random random = new Random();
int randIdx = 0;
for (int i=0; i < X; i++)
{
randIdx = randomStep * i + random.nextInt(randomStep);
dummyIndexes[i] = randIdx;
}
0
source to share