Skip to content

Instantly share code, notes, and snippets.

@DeveloperPaul123
Created March 11, 2021 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DeveloperPaul123/9d92067240a2e295fc6aef6637d04405 to your computer and use it in GitHub Desktop.
Save DeveloperPaul123/9d92067240a2e295fc6aef6637d04405 to your computer and use it in GitHub Desktop.
Simple std dev calculation using STL algorithms.
#include <iostream>
#include <numeric>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
int main()
{
std::vector<int> values{2, 4, 4, 4, 5, 5, 7, 9};
const auto sum = std::accumulate(values.begin(), values.end(), 0);
const double mean = static_cast<double>(sum) / static_cast<double>(values.size());
const auto sq_sum = std::accumulate(values.begin(), values.end(), 0.0, [mean](double sum, int value) {
return sum + std::pow(value - mean, 2.0);
});
const auto variance = sq_sum / static_cast<double>(values.size());
auto std_dev = std::sqrt(variance);
std::cout << std::to_string(std_dev) << std::endl;
return 0;
}
@DeveloperPaul123
Copy link
Author

Example calculation and explanation is here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment