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?
if you call
yesOrNo(0.75)
it will returntrue
75% of the time.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
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.You can easily implement this using the
rand
function: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 the75
for any probability you want.std::random_device
orboost::random
ifstd::random_device
is not implemented by your C++ compiler, using aboost::random
you can usebernoulli_distribution
to generate a randombool
value!As nobody here seems to listen, I'll write the correct answer myself.
Edited due to good comment.