-4

I need to implement a function int myRand(double p) which return 1 or 0.The probability it will return 1 is p ,while the probability it will return 0 is 1- p

4

3 回答 3

3

您可以std::discrete_distribution为此使用:

#include <random>

double p = 0.25;

std::random_device rd;
std::mt19937 gen(rd());
std::discrete_distribution<> distrib({ 1-p, p });
                                    // ^^^  ^- probability for 1
                                    //  | probability for 0
std::cout << distrib(gen);
于 2013-04-27T19:09:58.607 回答
2

double在 range 中生成一个随机数[0..1],然后执行以下操作:

int randomWithProb(double p) {
    double rndDouble = (double)rand() / RAND_MAX;
    return rndDouble > p;
}
于 2013-04-27T19:04:31.793 回答
1

您只需要从 [0,1] 生成一个随机浮点数。如果它 >p 则返回 1,否则返回 0。

于 2013-04-27T19:04:16.947 回答