I'm working on a project where I run actions randomly with a certain probability.
I basically have four actions. Action A
has a probability of 40%, Action B
has a probability of 40%, Action C
has a probability of 15% and Action D
has a probability of 5%.
My approach was to generate a random number (int) between 0 and 99 (100 possible integer values). Then run the actions accordingly, but the numbers don't add up for me.
The code is basically:
// values starting from 0 up to 99
randNumber=random(100);
// Probability of 40% (will enter for values including 59 up to 99 (40 numbers))
if (randNumber >= 59)
{
actionA();
}
// Probability of 40% (will enter for values including 18 up to 58 (40 numbers))
else if (randNumber >=18)
{
actionB();
}
// Probability of 15% (will enter for values including 2 up to 17 (15 numbers))
else if (randNumber >=2)
{
actionC();
}
// Remaining probability of what should be 5% (will enter for values including 0 to 1 (2 numbers)) ???
else
{
actionD();
}
Where am I going wrong? With values from 0 to 99, I should have 100 possible numbers. However, the last probability of the last 5% does not add up.
Source of random(): https://www.arduino.cc/reference/en/language/functions/random-numbers/random/
CodePudding user response:
As chiappar mentioned it is a math problem, not a code problem. But his solution is wrong.
To solve this you could remove the equal sign from >=
, but then you also have to update the values, so they will be as follows:
if (randNumber > 59)
if (randNumber >19)
if (randNumber >4)
else
CodePudding user response:
It actually depends on the source of random(int) function, you are not showing on your question, but I think your problem is more math-related than C -related, if actually random(int) is uniform between 0 and 99 included.
How many are >=59? I am quite sure there are 41, not 40, therefore you are giving a probability equal to 41%, not 40% (99 - 59 1 for the >=
). And 18<= x < 59
is quite the same, there actually are 41.
At the end of the day, you do not have numbers because every interval is 1 too much.
Try removing the equal from that >=
and rethink about your intervals accordingly, (59, 19 and so on)