0

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.

2
  • 3
    Your calculation of num right now forces it to be an int. Switching to nextInt won't change the precision at all. Any precision you're hoping for is already being discarded.
    – resueman
    Commented Aug 4, 2017 at 1:02
  • I fixed the code. I mistyped. That's what my code looks like
    – Jared
    Commented Aug 4, 2017 at 1:45

1 Answer 1

1
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.

1
  • I edited your code a bit to fit my needs and it worked. Thanks!
    – Jared
    Commented Aug 4, 2017 at 3:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.