数据结构中的二项式分布

二项分布是从N条伯努利路径中获得n次成功的离散概率分布Pp(n | N)(具有x = 0和x = 1标记的两个可能结果)。x = 1是成功,x = 0是成功发生的概率为p,失败发生的概率为q = 1 – p。)因此,二项分布可以写为

$$P_ {p} \ lgroup n \:\ arrowvert \ N \ rgroup = \ left(\ begin {array} {c} N \\ n \ end {array} \ right)p ^ {n} \ lgroup1-p \ rgroup ^ {Nn} $$

示例

#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;
   binomial_distribution<int> distribution(9,0.5);
   int p[10]={};
   for (int i=0; i<nrolls; ++i) {
      int number = distribution(generator);
      p[number]++;
   }
   cout << "binomial_distribution (9,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: