I need to select one possible output based on probabilities. lets say I have
p[1]=20%
p[2]=40%
p[3]=15%
p[4]=25%
the size of p[] is a variable (in this case 4) and I know that together they sum to 100%. how to select one element from p in accordance to it's probability?
asked Mar 25, 2014 at 21:11
user3453281
5995 silver badges12 bronze badges
1 Answer 1
The simplest way to use this is to use the Random.nextFloat() method for this, and then check which range the random number between 0-1 falls in.
Based on your question comments, you probably want something more like this:
Random r = new Random();
p[0]=0.2;
p[1]=0.4;
p[2]=0.15;
p[3]=0.25;
float myVal = r.nextFloat();
float probSum = 0.0;
for (int i = 0; i < p.length; p++) {
probSum += p[i];
if (myVal <= probSum) {
return i;
}
}
return p.length-1;
Obviously you can pretty this up, but this is a general idea that should work.
answered Mar 25, 2014 at 21:18
Taj Morton
1,6384 gold badges19 silver badges26 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
user3453281
I cannot code it like this because I do not know how many elemnts are in p[], so I wouldnt know how many else(if) brackets I need. what I know is that I have n elements and their probability add up to 100%. I also know their individual probability
Taj Morton
@user3453281 I've edited my answer to reflect that. Let me know if this is what you need.
user3453281
ooh this is pretty and is very much looks like it does what I need. I sum their individual probability until my I get to my random number. yeah that should works. thanks friend.
lang-java
if/elseits value and set your array accordently.