我有一个函数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
}
}
}
}
我期望第一个if语句以4p/5的概率输入,第二个if语句以p/5的概率输入
在现代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);
当我们需要使用它时:
if (d1(gen)) {
// replace nucleotide with 4p/5 probability
} else {
// something else with 1 - 4p/5 probability
}
相反,如果你想做一件事的概率是4p/5,然后,独立地,另一件事的概率是1p/5,这也很容易做到:
if (d1(gen)) {
// replace nucleotide with 4p/5 probability
}
if (d2(gen)) {
// something else with 1p/5 probability
}
详情见bernoulli_distribution