Based on the first answer in this question, I implemented a function that returns random numbers with a probability. However, the random numbers generated through this method are not following the probability described.
My code is given below
ArrayList<Integer> probsArray=new ArrayList<Integer>();
int count1=(int) (type1prob*100);
int total = 0;
total+=count1;
while(count1!=0){
probsArray.add(1);
count1--;
}
int count2=(int) (type2prob*100);
total+=count2;
while(count2!=0){
probsArray.add(2);
count2--;
}
int count3=(int) (type3prob*100);
total+=count3;
while(count3!=0){
probsArray.add(3);
count3--;
}
System.out.println("total is "+total);
int randomNum= ThreadLocalRandom.current().nextInt(0, total);
return probsArray.get(randomNum);
If I use the following input values
type1prob=0.5
type2prob=0.0
type3prob=0.5
Then the output I get is
Total type 1 = 25
Total type 2 = 0
Total type 3 = 20
There shouldnt be such a big difference between type 1 and type 3.
Aucun commentaire:
Enregistrer un commentaire