-2

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.

Aroonalok
  • 631
  • 1
  • 7
  • 18
  • 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 Answers1

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
    Caution, with a, b integers, a/b is 0. –  Feb 27 '18 at 10:54
  • 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
    You can bet the the OP will fall in the trap (your code is valid C/C++). –  Feb 27 '18 at 11:02
  • @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
  • @Yola Could you please explain why is `(rand() < p) ` a success? – Aroonalok Feb 28 '18 at 04:28
  • 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
    @Yola Many Thanks. That helped. – Aroonalok Feb 28 '18 at 05:54