คำอธิบาย
negative_binomial_distribution ใน <random> สร้างจำนวนล้มเหลว (failures) ก่อนได้ความสำเร็จ (successes) ครั้งที่ k ตามการแจกแจง negative binomial
- พารามิเตอร์: k (จำนวน success ที่ต้องการ), p (ความน่าจะเป็น success)
- คืนค่า: จำนวน failures ก่อนได้ k successes
ตัวอย่าง: จำลองการทอยเหรียญจนได้หัว 4 ครั้ง
#include <bits/stdc++.h>
using namespace std;
int main() {
const int trials = 10000;
const int scale = 100;
default_random_engine gen;
negative_binomial_distribution<int> dist(4, 0.5); // k=4, p=0.5
vector<int> freq(10, 0);
for(int i = 0; i < trials; i++) {
int failures = dist(gen);
if(failures < 10) freq[failures]++;
}
cout << "Negative Binomial Distribution (k=4, p=0.5):\n";
for(int i = 0; i < 10; i++) {
cout << i << ": " << string(freq[i] * scale / trials, '*') << endl;
}
return 0;
}
เอาต์พุตตัวอย่าง
Negative Binomial Distribution (k=4, p=0.5): 0: ***** 1: ************ 2: **************** 3: *************** 4: ************* 5: ********** 6: ******** 7: ***** 8: *** 9: **