DOWNLOAD
INTRODUCTION
Wanted to create a function to test whether a chance event with a given percentage success rate occurs or fails every time the function is run. Wanted it to be more true to real life. Where, for example, if something has a chance of happening 1 in 4 times, in real life it does not always happen once every four counts but averages out to 1 in 4 times over all (e.g. 4 counts= no, 16 counts=4, 36 counts=11, 100 counts = 25...).
The method I've used seems to work partially and is a compromise over using the more complicated poisson distribution stuff. See what you guys think.
DESCRIPTION
int getChance (double percSuccess)
The function generates a real random number between 0.0 and 100.0 and tests it against a low band and high band range based on a percentage success passed in via the function. If random number falls within either the low or high band, it returns a 1. Indicating the chance event has occurred. Otherwise returns a 0 for a failed chance event.
USAGE
To run a code for an event with a success rate chance of 27.25% use:-
- Code: Select all
if (getChance(27.25))
{
// your code to do something
}
GLOBAL CODE
- Code: Select all
int getChance(double percSuccess)
{
int chance=0;
double randNum=rand(100.0);
double lowBand=percSuccess/2.0;
double highBand=100.0-(percSuccess/2.0);
if (percSuccess<0.0) { percSuccess=0.0; }
if (percSuccess>100.0) { percSuccess=100.0; }
if(((randNum>=0.0)&&(randNum<=lowBand))||((randNum>=highBand)&&(randNum<=100.0)))
{
chance=1;
}
return chance;
}
Feel free to play with the code and let me know if you get it to work better (i.e. more true to real life).