Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers with different probabilities [duplicate]

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?

like image 712
Josh Brittain Avatar asked Oct 14 '12 18:10

Josh Brittain


4 Answers

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.

like image 175
Luchian Grigore Avatar answered Nov 15 '22 20:11

Luchian Grigore


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.

like image 28
111111 Avatar answered Nov 15 '22 19:11

111111


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!

like image 44
BigBoss Avatar answered Nov 15 '22 19:11

BigBoss


#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.

like image 20
Ionut Hulub Avatar answered Nov 15 '22 20:11

Ionut Hulub