I have N values (integer). I'd like to know what is the most elegant way to randomly pick one of those values regarding a percentage. For example, for a 3 values example:
I need this for a program i'm developing with Java but a pseudo code algorithm or a code in any other language would be ok.
If you want to use RAND to generate a random number but don't want the numbers to change every time the cell is calculated, you can enter =RAND() in the formula bar, and then press F9 to change the formula to a random number.
As the term suggests, a random number is a number chosen by chance -- i.e., randomly, from a set of numbers. All the numbers in a specified distribution have equal probability of being chosen randomly.
One way of doing this without calculating values to use is
double d = Math.random() * 100;
if ((d -= 30) < 0) return 1;
if ((d -= 12) < 0) return 2;
if ((d -= 45) < 0) return 3;
return 4;
Proposed algorithm:
n
) between 0
and 1
(assuming your random generator is well distributed)n < 0.30
return value 1
n < 0.42
return value 2
n < 0.87
return value 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With