简体   繁体   中英

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;
}
std::mt19937 rng(std::random_device{}());
std::bernoulli_distribution d(0.005);
bool b = d(rng); // true 0.5% of the time; otherwise false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM