Possible Duplicate:
C++ function for picking from a list where each element has a distinct probability
I need to randomly determine a yes or no outcome (kind of a coin flip) based on a probability that I can define (.25, .50, .75).
So for example, I want to randomly determine yes or no where yes has a 75% chance of being chosen. What are my options for this? Is there a C++ library I can use for this?
You can easily implement this using the rand
function:
bool TrueFalse = (rand() % 100) < 75;
The rand() % 100
will give you a random number between 0 and 100, and the probability of it being under 75 is, well, 75%. You can substitute the 75
for any probability you want.
Check at the C++11 pseudo random number library.
http://en.cppreference.com/w/cpp/numeric/random
http://en.wikipedia.org/wiki/C%2B%2B11#Extensible_random_number_facility
std::random_device rd;
std::uniform_int_distribution<int> distribution(1, 100);
std::mt19937 engine(rd()); // Mersenne twister MT19937
int value=distribution(engine);
if(value > threshold) ...
like this, then say all above 75 is true, and all below is false, or whatever threshold you want
Unlike rand
you can actually control the properties of the number generation, also I don't believe rand as used in other answers (using modulo) even presents a uniform distribution, which is bad.
std::random_device
or boost::random
if std::random_device
is not implemented by your C++ compiler, using a boost::random
you can use bernoulli_distribution
to generate a random bool
value!
As nobody here seems to listen, I'll write the correct answer myself.
std::mt19937 e(std::random_device());
std::bernoulli_distribution d(0.75);
if (d(e))
// ...
Edited due to good comment.
#include <cstdlib>
#include <iostream>
using namespace std;
bool yesOrNo(float probabilityOfYes) {
return rand()%100 < (probabilityOfYes * 100);
}
int main() {
srand((unsigned)time(0));
cout<<yesOrNo(0.897);
}
if you call yesOrNo(0.75)
it will return true
75% of the time.