9

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?

4

4 に答える 4

25

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.

于 2012-10-14T18:47:54.940 に答える
8

C++11疑似乱数ライブラリを確認してください。

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

このように、75を超えるものはすべて真であり、下のものはすべて偽であると言います。

数値生成のプロパティを実際に制御できるのとは異なりrand、他の回答(モジュロを使用)で使用されているランドが一様分布でさえあるとは思わないので、これは悪いことです。

于 2012-10-14T18:48:07.633 に答える
3

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!

于 2012-10-14T18:56:00.793 に答える
1
#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);
}

電話をかけると、75%の確率yesOrNo(0.75)で返されます。true

于 2012-10-14T18:50:37.027 に答える