I'd like to randomly generate a YES or NO based on a percentage
So I want to "roll" and have a 25% chance to hit YES, a 75% chance to hit NO
Was hoping someone could point me in the right direction on the best way to do this, maybe some article or something?
All of the other answers seem to focus on the percentage of YES being 25%, which is a probability of 1/4. But what if the percentage is an arbitrary integer between 0 and 100?
BOOL randomBoolWithYesPercentage(int percentage) {
return arc4random_uniform(100) < percentage;
}
Call it with the percentage, like randomBoolWithYesPercentage(25)
.
And what if the percentage can be fractional, like 37.6%? Then we need to get more sophisticated. This should suffice:
BOOL randomBoolWithYesPercentage(double percentage) {
double r = 100 * (double)arc4random() / ((double)UINT32_MAX + 1);
return r < percentage;
}
Use a random function with an equal distribution and make it as likely as you want to equal one of the possible values
BOOL RollWithDenominator(NSInteger denominator)
{
return 0 == arc4random_uniform(denominator);
}
For a 1/4 chance call RollWithDenominator(4);
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