1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream> // std::cou
#include <algorithm> // std::transform
double calc_sum_of_squares1(std::vector<double> & vld);
double calc_sum_of_squares2(std::vector<double> & vld);
int sq(int c, int d) {return c+d*d;}
int main () {
std::vector<double> vld1 { 600,470,170,430, 300};
std::vector<double> vld2 { 3, 21, 98, 203, 17, 9};
double sum_of_squares = calc_sum_of_squares1(vld1); // http://www.mathsisfun.com/data/standard-deviation.html
std::cout << "Variance 1: " << sum_of_squares/vld1.size() << " Std Deviation 1: " << sqrt(sum_of_squares/vld1.size()) << std::endl;
sum_of_squares = calc_sum_of_squares2(vld2); // http://www.statisticshowto.com/how-to-find-the-sample-variance-and-standard-deviation-in-statistics/
std::cout << "Variance 2: " << sum_of_squares/(vld2.size()-1) << " Std Deviation 2: " << sqrt(sum_of_squares/(vld2.size()-1)) << std::endl;
return 0;
}
// http://www.mathsisfun.com/data/standard-deviation.html
double calc_sum_of_squares1(std::vector<double> & vld) {
double mean = std::accumulate(begin(vld), end(vld), 0.0) / vld.size();
std::vector<double> diff(vld.size());
std::transform(begin(vld), end(vld), begin(diff), std::bind2nd(std::minus<double>(), mean));
return std::inner_product(begin(diff), end(diff), begin(vld), 0.0);
}
// http://www.statisticshowto.com/how-to-find-the-sample-variance-and-standard-deviation-in-statistics/
double calc_sum_of_squares2(std::vector<double> & vld) {
double sum = std::accumulate(begin(vld), end(vld), 0.0); // step1
sum = (sum*sum) / vld.size(); // step 2
sum = std::accumulate(begin(vld), end(vld), 0.0, sq) - sum; // step3&4
return sum; // step5&6 occur after return
}
|