1 定义
(1)均值
(2)方差
(3)标准差
2 代码实现
//std::vector< double> 或者 std::vector< int> 类型变量求均值和方差
#include <numeric>
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
int main()
{// 求均值vector<double> A = {1,2,3,4,5,6};double sum = std::accumulate(std::begin(A), std::end(A), 0.0);double mean = sum / A.size();// 求方差与标准差double variance = 0.0;for (uint16_t i = 0 ; i < A.size() ; i++){variance = variance + pow(A[i]-mean,2);}variance = variance/A.size();double standard_deviation = sqrt(variance);std::cout<<mean<<std::endl; // 均值std::cout<<variance<<std::endl; // 方差std::cout<<standard_deviation<<std::endl; // 标准差
}
3 代码结果
3.5
2.91667
1.70783
4 为方便使用,可以将求方差封装为一个函数
代码如下
#include <numeric>
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
double
VectorVar(const vector<double> &A)
{double sum = accumulate(begin(A),end(A), 0.0);double mean = sum / A.size();// 求方差与标准差double variance = 0.0;for (uint16_t i = 0 ; i < A.size() ; i++){variance = variance + pow(A[i]-mean,2);}variance = variance/A.size();return variance;
}int main()
{vector<double> A = {1,2,3,4,5,6};cout<<VectorVar(A)<<endl;
}
运行结果
2.91667