What does it mean in terms of implementation when we say we choose something with probability a/b? An explanatory solution will be a great help.
Asked
Active
Viewed 84 times
-2
-
Check this question [Probability Random Number Generator](https://stackoverflow.com/questions/3016439/probability-random-number-generator) and its answers! – Bassem Feb 27 '18 at 10:05
1 Answers
2
Probability p = a/b
means that from b
trials you have a
successes.
You can model it as the following:
float p = static_cast<float>(a)/b;
if (rand() < p) { // rand() returns uniform random value between 0 and 1.
// handle success
}
else {
// handle fail
}

Yola
- 18,496
- 11
- 65
- 106
-
Note that in case of non-intersected probabilities, you need to define ranges for each one. – Bassem Feb 27 '18 at 10:09
-
1
-
1@YvesDaoust if a/b is 0 then we will never get into branch for successes and that's expected. If you mean that integer division might happen and only then cast to float will occur, then I didn't added any casts as i thought it to be logical example, not really production code. Do you think i need to add appropriate cast? – Yola Feb 27 '18 at 11:00
-
1
-
@YvesDaoust I am more interested in the line of thought that is taken to translate the mathematics to code. a,b belonging to Integers was put from a mathematical point of view. I have removed them now, for from a computational point of view, the answer is Zero. But that is secondary. – Aroonalok Feb 28 '18 at 04:24
-
-
1@Aroonalok let's do a concrete example, `b = 10`, `a = 6`, so you have to choose something with probability `p = 0.6`. If `rand()` returns uniform number in range between 0 and 1, then the probability that returned value will be less than `0.6` is exactly `0.6`. – Yola Feb 28 '18 at 05:40
-
1