我正在考慮一個有任意數量的人的社會。每個人只有兩個選擇。要麼他或她保持現有的選擇,要麼轉換。在我想寫的代碼中,用戶切換的人的概率是由用戶輸入的。計算與二項和相似的條件概率
爲了明確我想要做的事情,假設用戶告訴計算機,社會中有3個人每個人選擇切換的概率由(p1,p2,p3)給出。考慮人1,他有切換的概率p1。使用他作爲我們計算的基礎,給定人1作爲基礎的概率,社會中恰好沒有人選擇切換的概率由下式給出:
P_ {1}(0)=(1-p2)*( 1-P3)
和使用人1作爲基礎的概率,即恰好一個人在社會選擇切換由
P_ {1}(1)= P2 *(1-P3)中給出+(1-P2)* P3。
我無法弄清楚如何在C++中編寫這個概率函數,而不用寫出總和中的每一項。我考慮使用二項式係數,但由於取決於用戶輸入,我無法弄清楚總和的閉合表達式表達式,所以需要考慮任意多的概率。
我附上了我所擁有的東西。概率函數只是我試圖做的一部分,但它也是最難的部分。我將概率函數概率命名爲probab,並且我在函數內for循環中的內容顯然是錯誤的。
編輯:基本上我想計算選擇一個子集的概率,其中該子集中的每個元素具有不同的被選擇概率。
我希望有關如何去解決這個問題的任何提示。請注意,我是C++的初學者,因此有關提高我的編程技能的任何提示也值得讚賞。
#include <iostream>
#include <vector>
using namespace std;
unsigned int factorial(unsigned int n);
unsigned int binomial(unsigned int bin, unsigned int cho);
double probab(int numOfPeople, vector<double> probs, int p, int num);
int main() {
char correctness;
int numOfPeople = 0;
cout << "Enter the # of people: ";
cin >> numOfPeople;
vector<double> probs(numOfPeople); // Create a vector of size numOfPeople;
for (int i = 1; i < numOfPeople+1; i++) {
cout << "Enter the probability of person "<< i << " will accept change: ";
cin >> probs[i-1];
}
cout << "You have entered the following probabilities of accepting change: (";
for (int i = 1; i < numOfPeople+1; i++) {
cout << probs[i-1];
if (i == numOfPeople) {
cout << ")";
}
else {
cout << ",";
}
}
cout << endl;
cout << "Is this correct? (Enter y for yes, n for no): ";
cin >> correctness;
if (correctness == 'n') {
return 0;
}
return 0;
}
unsigned int factorial(unsigned int n){ // Factorial function
unsigned int ret = 1;
for(unsigned int i = 1; i <= n; ++i) {
ret *= i;
}
return ret;
}
unsigned int binomial(unsigned int totl, unsigned int choose) { // Binomial function
unsigned int bin = 0;
bin = factorial(totl)/(factorial(choose)*factorial(totl-choose));
return bin;
}
double probab(int numOfPeople, vector<double> probs, int p, int num) { // Probability function
double prob = 0;
for (int i = 1; i < numOfPeople; i++) {
prob += binomial(numOfPeople, i-1)/probs[p]*probs[i-1];
}
return prob;
}
很高興聽到你發現它照亮! – Calle
順便說一句,這裏是關於Math.SE的問題(帶答案):http://math.stackexchange.com/questions/731721/probability-of-choosing-a-subset-of-elements-where-each-元件具有-A-不同 – Calle