数据结构中的负二项分布
负二项分布是一种可以根据负二项离散分布产生整数的随机数分布。这称为帕斯卡分布,因此负二项分布可以写成
$$P\lgroup i\arrowvert k,p\rgroup=\lgroup \frac{k+i-1}{i}\rgroup p^{k}\lgroup 1-p\rgroup^{i}$$
示例
#include <iostream> #include <random> using namespace std; int main(){ const int nrolls = 10000; // number of rolls const int nstars = 100; // maximum number of stars to distribute default_random_engine generator; negative_binomial_distribution<int> distribution(3,0.5); int p[10]={}; for (int i=0; i<nrolls; ++i) { int number = distribution(generator); if (number<10) p[number]++; } cout << "negative_binomial_distribution (3,0.5):" << endl; for (int i=0; i<10; ++i) cout << i << ": " << string(p[i]*nstars/nrolls,'*') << endl; }
输出
0: ************ 1: ******************* 2: ***************** 3: **************** 4: *********** 5: ******* 6: ***** 7: *** 8: ** 9: *
广告