使用概率输入 If 语句

Dan*_*obo 5 c++ probability

我的函数 mutateSequence 接受三个参数。参数p是0和1之间的值,包括0和1。我需要两个 if 语句,一个以 4p/5 的概率输入,另一个以 p/5 的概率输入。我该如何编写逻辑来实现这一点?

代码:

void mutateSequence(vector<pair<string, string>> v, int k, double p)
{
       for (int i = 0; i < k - 1; i++)
    {
        string subjectSequence = v[i].second;
        for (int j = 0; j < subjectSequence.length(); j++)
        {
            // with probability 4p/5 replace the nucelotide randomly
            if (//enter with probability of 4p/5)
            {
               //do something
            }
            if (//enter with probability of p/5)
            {
                //do something
            }
          
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我期望第一个 if 语句以 4p/5 的概率输入,第二个 if 语句以 p/5 的概率输入

Edw*_*ard 7

在现代 C++ 中有一种非常简单的方法可以做到这一点。首先我们进行设置:

#include <random>
std::random_device rd;
std::mt19937 gen(rd());
// p entered by user elsewhere
// give "true" 4p/5 of the time
std::bernoulli_distribution d1(4.0*p/5.0);
// give "true" 1p/5 of the time
std::bernoulli_distribution d2(1.0*p/5.0);
Run Code Online (Sandbox Code Playgroud)

然后当我们想要使用它时:

if (d1(gen)) {
    // replace nucleotide with 4p/5 probability
} else {
    // something else with 1 - 4p/5 probability
}
Run Code Online (Sandbox Code Playgroud)

相反,如果您想以 4p/5 的概率做一件事,然后独立地以 1p/5 的概率做另一件事,这也很容易完成:

if (d1(gen)) {
    // replace nucleotide with 4p/5 probability
} 
if (d2(gen)) {
    // something else with 1p/5 probability
}
Run Code Online (Sandbox Code Playgroud)

bernoulli_distribution详情请参阅。

  • 如果“gen”设置为“d(gen)”给出 4p/5 的概率,那么“!d(gen)”给出 1-4p/5 的概率,而不是 1p/5。 (2认同)