0

I have an event that should have a 0.5% probability of occurring (not very often).

How can I generate a random number based on this probability?

Would something like this be sufficient, I don't believe so as srand returns an integer...

double rate = 0.05;
if((srand() % 100) < rate)
{
    std::cout << "Event Occurred" << endl;
}
Ricky
  • 823
  • 2
  • 14
  • 31
  • 3
    `srand` doesn't generate random numbers; `rand` does. – Matthew Moss Mar 20 '15 at 20:39
  • possible duplicate of [How to obtain a value based on a certain probability](http://stackoverflow.com/questions/3572343/how-to-obtain-a-value-based-on-a-certain-probability) – Matthew Moss Mar 20 '15 at 20:39
  • 1
    @MatthewMoss's dup is correct, but wanted to add that the trick is remembering that a 0.05% probability is equivalent to saying a 5/10000 probability. In other words, you just have to scale your values appropriately so that everything is an integer. – aruisdante Mar 20 '15 at 20:41
  • The answers in that dup are terrible. – T.C. Mar 20 '15 at 20:47
  • 1
    As of C++11, you normally want to use something like `uniform_int_distribution` to get the numbers into a range. If your compiler is old enough it doesn't include that, there are [other answers](http://stackoverflow.com/a/10219422/179910) that at least tell how to do that part correctly. – Jerry Coffin Mar 20 '15 at 20:58

1 Answers1

4
std::mt19937 rng(std::random_device{}());
std::bernoulli_distribution d(0.005);
bool b = d(rng); // true 0.5% of the time; otherwise false
T.C.
  • 133,968
  • 17
  • 288
  • 421