数据结构中的二项分布
二项分布是离散概率分布 Pp(n | N),用于从 N 次伯努利试验(有两种可能的结果,标记为 x = 0 和 x = 1。x = 1 是成功,x = 0 是失败。成功的概率是 p,失败的概率是 q,q = 1 – p。)因此,二项分布可以写成
$$P_{p}\lgroup n\:\arrowvert\ N\rgroup=\left(\begin{array}{c}N\ n\end{array}\right) p^{n}\lgroup1-p\rgroup^{N-n}$$
示例
#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:
广告