負の二項分布サンプリング; Negative Binomial Distribution Sampling
概要
負の二項分布とは以下の式で表現される確率分布。確率\(p\)で起きる事象が\(N\)回起きるまでに要した試行回数\(k\)の確率を示す。
$$ P[X=k] = {}_{k-1} \mathrm{C}_{N-1} p^N (1-p)^{k-N}, \quad k \geq N $$
ソースコード
namespace ExRandom.Discrete {
class NegativeBinomialRandom : Random{
readonly BernoulliRandom bd;
readonly int r, max;
public NegativeBinomialRandom(MT19937 mt, double prob = 0.5, int r = 4, int max = int.MaxValue) {
if(mt == null) {
throw new ArgumentNullException();
}
if(max < 1 || r < 1) {
throw new ArgumentException();
}
this.bd = new BernoulliRandom(mt, prob);
this.r = r;
this.max = max;
}
public NegativeBinomialRandom(MT19937 mt, decimal prob, int r = 4, int max = int.MaxValue) : this(mt, (double)prob, r, max){
}
public override int Next() {
int cnt = 0;
for(int i = 1; i < max; i++) {
if(bd.NextBool()) {
cnt++;
if(cnt >= r) {
return i - cnt;
}
}
}
return int.MaxValue;
}
}
}
関連項目
メルセンヌ・ツイスタ
各種確率分布サンプリング基本クラス