If you ever need a Java method that returns a boolean value based on a given probability, I can confirm that this method works:
/**
* `probability` should be given as a percentage, such as
* 10.0 (10.0%) or 25.5 (25.5%). As an example, if `probability`
* is 60% (60.0), 100 calls to this function should return ~60
* `true` values.
* (Note that Math.random returns a value >= 0.0 and < 1.0.)
*/
static boolean getRandomBoolean(float probability) {
double randomValue = Math.random()*100; //0.0 to 99.9
return randomValue <= probability;
}
As noted in the comments, if the method is given a probability
of 60.0 and it’s called 100 times, on average it will return the value true
60 times, and false
40 times. Put another way, if you want a boolean value about 60% of the time, call this method with the value 60.0
.
Calling the method
I use this boolean probability method with my Java/Android football game. I specifically use it when a user wants to kick a field goal, in which case the getRandomBoolean
method is called like this:
public static boolean fieldGoalWasGood(int distance) {
float fgAccuracy = 0f;
if (distance < 20) fgAccuracy = 99f;
else if (distance < 30) fgAccuracy = 98f; //20-29
else if (distance < 40) fgAccuracy = 96f; //30-39
else if (distance < 45) fgAccuracy = 93f; //40-44
else if (distance < 50) fgAccuracy = 90f; //45-49
else if (distance < 55) fgAccuracy = 80f; //50-54
else if (distance < 60) fgAccuracy = 33f; //55-59
else if (distance < 64) fgAccuracy = 8f; //60-63
else fgAccuracy = 0f;
return getRandomBoolean(fgAccuracy);
}
I prefer to deal in probability values from 0 to 100%, which is why I convert the value r
from (a) 0.0 to 1.0 to (b) 0.0 to 100.0 in getRandomBoolean
.
In summary, if you ever need a Java method/function that returns a boolean value based on a given probability, I hope this source code is helpful.