반응형

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

 

출처 - https://stackoverflow.com/questions/7616511/calculate-mean-and-standard-deviation-from-a-vector-of-samples-in-c-using-boos

 

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

 

반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts