การแจกแจงแบบทวินามเป็นการแจกแจงความน่าจะเป็นแบบไม่ต่อเนื่อง Pp(n | N) ของการได้รับ n ความสำเร็จจากเส้นทาง No Bernoulli (มีสองผลลัพธ์ที่เป็นไปได้ที่มีป้ายกำกับโดย 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: