#偷懒系列#概统:组合数概率相关
缘起做概统作业的时候,需要计算一些二项分布相关的E(x)(数学期望), V(x)(方差)等,由于涉及到组合数,计算量相当大,于是诞生了以下这个小工具。演示上图就是计算∑ i=0 20 C(20,i)p i (1−p) ( n−i ) \sum_{i=0}^{20} C(20, i)p^i(1-p)^(n-i^) 有关的。源代码可以到我的github:https://github.com
·
缘起
做概统作业的时候,需要计算一些二项分布相关的E(x)(数学期望), V(x)(方差)等,由于涉及到组合数,计算量相当大,于是诞生了以下这个小工具。
演示
上图就是计算
∑i=020C(20,i)pi(1−p)(n−i)
有关的。
源代码
可以到我的github:https://github.com/LoHiaufung/Lazy.git, 文件名为:CombinationalNumber.cpp
或者复制粘贴以下源代码:
#include <iostream>
#include <math.h>
using namespace std;
int main () {
int n;
cout << "Type in n: ";
cin >> n;
double* c = new double[n+1];
c[0] = 1;
for (int i = 1; i < n+1; i++) {
c[i] = c[i-1] / i * (n - i + 1);
}
double successProbability;
cout << "Type in the success probability: ";
cin >> successProbability;
// 每个i对应的概率
double* sp = new double[n+1];
for (int i = 0; i < n + 1; i++) {
sp[i] = c[i] * pow(successProbability, i) * pow(1 - successProbability, n - i);
}
//所求的加权、不加权部分和的起止[begin, end]
int begin, end = 0;
cout << "To get the sum,the begin index: ";
cin >> begin;
cout << "To get the sum,the end index: ";
cin >> end;
// 无权部分和
double sum = 0;
for (int i = begin; i < end + 1; i++) {
sum += sp[i];
}
cout << "[begin, end] sum of probability is: " << sum << endl;
// 加权部分和
double sumWithWeight = 0;
for (int i = begin; i < end + 1; i++) {
sumWithWeight += sp[i] * i;
}
cout << "[begin, end] sum of probability with weight is: " << sumWithWeight << endl;
// 数学期望
double expectedValue = 0;
for (int i = 0; i < n + 1; i++) {
expectedValue += sp[i] * i;
}
cout << "[0, n] sum expected value is: " << expectedValue << endl;
// 方差
double variance = 0;
for (int i = 0; i < n + 1; i++) {
variance += (i - expectedValue) * (i - expectedValue) * sp[i];
}
cout << "[0, n] the variance is: " << variance << endl;
cout << "[0, n] the standard deviation is: " << sqrt(variance) << endl;
delete[] c;
delete[] sp;
return 0;
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)