While reviewing a colleagues code for a hard to identify bug, I encountered what for me is a new design pattern for triggering events with a given probability. In the past when needing to trigger an event with a certain probability, say 5% I would also use a code snippet like the following:
event = random(100);
if (event < 5)
Event Happened.
However, my colleague used the following approach:
if (random(20) == random(20))
Event Happended
At first, it seemed counter intuitive that his approach would produce a 5% chance of the event occurring, but looking at the math and running a few simulations proved that it would... Has anyone else ever seen this design pattern? What advantages does it have?
Oh, and for those of you interested in seeing that it works you can run this sketch...
int chance;
int gambler, house;
long hits=0;
long total=0;
float odds;
void DisplayResults(long h, long t, float o)
{
Serial.print("Hits = ");
Serial.print(h);
Serial.print(", Total = ");
Serial.print(t);
Serial.print(", Chance = ");
Serial.print(o);
Serial.print(", Should = ");
Serial.println(0.05);
}
void setup()
{
Serial.begin(115200);
chance = 20; // Represent a 5% chance 1/0.05
randomSeed(analogRead(0));
}
void loop()
{
gambler = random(chance);
house = random(chance);
total++;
if (gambler == house)
{
hits++;
odds = hits / (1.0 * total);
DisplayResults(hits, total, odds);
}
}