Random numbers with different probabilities [dupli

2019-02-03 19:10发布

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?

5条回答
放我归山
2楼-- · 2019-02-03 19:44
#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.

查看更多
太酷不给撩
3楼-- · 2019-02-03 19:52

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.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-02-03 19:53

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.

查看更多
Luminary・发光体
5楼-- · 2019-02-03 19:59

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!

查看更多
家丑人穷心不美
6楼-- · 2019-02-03 20:02

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.

查看更多
登录 后发表回答