Ricky
Ricky

Reputation: 883

In C++, How Can I Generate A Random Number Based Off Of A Double Value Probability?

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;
}

Upvotes: 0

Views: 120

Answers (1)

T.C.
T.C.

Reputation: 137315

std::mt19937 rng(std::random_device{}());
std::bernoulli_distribution d(0.005);
bool b = d(rng); // true 0.5% of the time; otherwise false

Upvotes: 4

Related Questions