C++의 vector에 저장된 값으로 부터 표준편차와 평균을 구하는 예제 코드입니다.
2021. 10. 10 - 최초작성
#include <iostream>
#include <numeric>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v = {1, 2, 3, 4, 5};
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();
std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; });
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
double stdev = std::sqrt(sq_sum / v.size());
cout << "mean : " << mean << endl;
cout << "stdev : " << stdev << endl;
}
실행 결과
mean : 3 stdev : 1.41421 |
Calculate mean and standard deviation from a vector of samples in C++ using Boost
Is there a way to calculate mean and standard deviation for a vector containing samples using Boost? Or do I have to create an accumulator and feed the vector into it?
stackoverflow.com