Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ตัวแปรสุ่มแบบ Binomial (Binomial Random Variables) ใน C++

ความรู้เบื้องต้น

Random Variables คือตัวแปรที่เป็นผลลัพธ์ของกระบวนการที่มีโอกาสให้ผลลัพธ์หลายอย่าง เช่น โยนเหรียญ (Head/Tail)

Binomial Random Variable คือตัวแปรสุ่มพิเศษที่มีคุณสมบัติ:

  • จำนวนการทดลองคงที่ (n)
  • ผลลัพธ์แต่ละครั้งมี 2 แบบ: สำเร็จ/ล้มเหลว
  • ความน่าจะเป็นสำเร็จคงที่ (p) ทุกครั้ง
  • การทดลองแต่ละครั้งเป็นอิสระต่อกัน

สูตรความน่าจะเป็น

P(X = k) = n! / (k! (n-k)!) * p^k * (1-p)^(n-k)

ค่าคาดหวัง: E[X] = np

ความแปรปรวน: Var[X] = np(1-p)

ตัวอย่างโค้ด C++

#include <iostream>
#include <cmath>
using namespace std;

int combination(int n, int r) {
    if (r > n / 2) r = n - r;
    int answer = 1;
    for (int i = 1; i <= r; i++) {
        answer *= (n - r + i);
        answer /= i;
    }
    return answer;
}

float randombinomialProbability(int n, int k, float p) {
    return combination(n, k) * pow(p, k) * pow(1 - p, n - k);
}

int main() {
    int n = 10;
    int k = 5;
    float p = 1.0 / 3;
    float binomialRandomVariable = randombinomialProbability(n, k, p);
    cout << "Probability of " << k;
    cout << " heads when a coin is tossed " << n;
    cout << " times where probability of each head is " << p;
    cout << " is = " << binomialRandomVariable << endl;
}

ผลลัพธ์

Probability of 5 heads when a coin is tossed 10 times where probability of each head is 0.333333 is = 0.136565