# Generate weighted random numbers, nextGaussian ()

Printable View

• 03-25-2011, 01:42 PM
graympa
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.
• 03-25-2011, 05:49 PM
imorio
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:

Code:

```Random randomnumber = new Random(); double randomChoice=randomnumber.getNextDouble(); int counter=0; double oddsTraversed=oddsValues[0]; while(oddsTraversed<randomChoice) { oddsTraversed+=oddsValues[++counter] } return counter;```
• 03-25-2011, 10:36 PM
graympa
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.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;