Thread: Generate weighted random numbers, nextGaussian ()

1. Member Join Date
Mar 2011
Posts
9
Rep Power
0 Generate weighted random numbers, nextGaussian ()

I would like to randomly pick an element from an array. I can create a random number in a range: Min + (int)(Math.random() * ((Max - Min) + 1)); but I want to weight the random numbers to have more lower numbers.
The random function nextGaussian() generates a random number with normal distribution (which is what I want), but the upper limit isn't one. When I ran some tests, I got numbers as high as 2.1. Theoretically, there isn't an upper limit. How can I use this to generate an int for the array? I think I can use some If statements, but that seems both clunky and non random. here is my code:

Random randomnumber = new Random();
return (int)(Math.abs((randomnumber.nextGaussian()* (double)arraylength)));
where arraylength is the number of elements in my array.
I used abs since nextGaussian gives me a both neg and pos numbers.  Reply With Quote

2. Senior Member Join Date
Aug 2010
Posts
127
Rep Power
0 Since you are working with discrete values (every position in the array is a natural number), you could just assign probabilities to each position.

For example::
position 1: odds of getting it should be 0.05
position 2: odds of getting it should be 0.04
....
...

put al those odds in an array (say "oddsValues") and then do something like this:

Java Code:
Random randomnumber = new Random();
double randomChoice=randomnumber.getNextDouble();
int counter=0;
double oddsTraversed=oddsValues;
while(oddsTraversed<randomChoice)
{
oddsTraversed+=oddsValues[++counter]
}
return counter;  Reply With Quote

3. Member Join Date
Mar 2011
Posts
9
Rep Power
0 Thanks very much. Since I wanted to keep my array length flexible, I have implemented it this way. I am a newb, so if you see anything wrong or could be improved, please let me know.

//I have added 1 to arraylength to allow cumultative function below
double [] oddsValues = new double[arraylength];
int sumOfArrayLength=0;

for(int i=1; i<arraylength ;i++)
{
oddsValues[i]=i;
sumOfArrayLength+=i;
}

//converts array element i into probability (as double) by dividing array
// element number by sum of all array numbers, then makes it
//cumultative by adding previous value(oddsValues[i-1])

oddsValues = 0.0;
for(int i=1; i<arraylength ;i++)
{
oddsValues[i]=(oddsValues[i]/sumOfArrayLength) + oddsValues[i-1];
}

Random randomnumber = new Random();
double randomChoice=randomnumber.nextDouble();
int counter=0;
while(randomChoice>oddsValues[counter])
{
counter++;
}
return counter;  Reply With Quote

Tags for this Thread

random element from array, weighted  Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•