Jared
Jared

Reputation: 2217

Android Random Numbers Issue

I am generating random numbers and I am having a equal distribution issue. The first and last numbers in the range always have half the change of getting chosen because they don't have that possibility of being rounded to on both sides.

For example, if the user chooses a min of 1 and a max of 10, 1 and 10 will have a decreased chance of getting picked compared to the others.

Here is my current code:

double num = random.nextDouble() * (max - min) + min;
String finalNum = String.format("%." + precision + "f", num);

I know I could fix this by using a nextInt() instead but the problem is that I want to keep it a double because the user selects how many decimal places there will be.

Help is appreciated.

Upvotes: 0

Views: 98

Answers (1)

Angel Koh
Angel Koh

Reputation: 13505

double min = 1.0;
double max = 10.0;
double rand = r.nextDouble();
//now we add 1 for the spread (we want the number to be from 0.5 to 10.5)
double range = max - min + 1;  
rand *=range;
//now we shift by an offset of min-0.5;
rand += (min -0.5);
//now we round the number
int intRand = Math.round(rand);

you can use rand (double) for displaying your precision and use intRand (int) for your integer random.

Upvotes: 1

Related Questions