Created
March 11, 2021 21:27
-
-
Save DeveloperPaul123/9d92067240a2e295fc6aef6637d04405 to your computer and use it in GitHub Desktop.
Simple std dev calculation using STL algorithms.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example calculation and explanation is here.