Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How choose random number within range, but weighted toward one part of that range? (in Java)

I want to choose random numbers within a range of numbers, but with weighting towards part of that range. For example:

  1. Choose random number between 1-10
  2. Weight it so that 1-5 is maybe 20% more likely than 6-10

Is this possible? How would I do this?

like image 836
Don Rhummy Avatar asked Oct 14 '25 07:10

Don Rhummy


2 Answers

It depends on how you want your probability distribution to look like.

For example:

Pick a random number between 1-10
If it is <= 6
    Return a random number between 1-5
Else
    Return a random number between 6-10
EndIf

Picks a number in 1-5 60% of the time and a number in 6-10 40% of the time.

like image 143
trutheality Avatar answered Oct 16 '25 20:10

trutheality


To generate a bell curve of probabilities, roll and sum multiple dice. Then subtract the average. Re-roll if the result is negative. The more dice rolled, the more weighting.

Here's one way, wholly untested.

float sum;
do {
   sum = rollThreeDice(); // returns 3 to 18, with an average is 10.5
   sum -= 10.5;           // Now the range is 0 to 7.5, with the lower end being more likely.
   } while(sum < 0);
return sum;

Of course you can roll dice with any number of sides in order to produce the desired range. You control the frequency curve by choosing the number of dice.

like image 41
Tony Ennis Avatar answered Oct 16 '25 20:10

Tony Ennis