Skip to content

Instantly share code, notes, and snippets.

@denkiwakame
Created February 10, 2014 07:09
Show Gist options
  • Save denkiwakame/8911609 to your computer and use it in GitHub Desktop.
Save denkiwakame/8911609 to your computer and use it in GitHub Desktop.
mean, variance, standard dev
#include <iostream>
#include <cmath>
#include <vector>
#include <list>
#include <numeric>
template <template<class T, class Allocator = std::allocator<T> > class Container>
double mean(Container<double> & x)
{
return std::accumulate(x.begin(), x.end(), 0.0) / x.size();
}
template <template<class T, class Allocator = std::allocator<T> > class Container>
double var(Container<double> & x)
{
double size = x.size();
double x_mean = mean(x);
return (std::inner_product(x.begin(), x.end(), x.begin(), 0.0) - x_mean * x_mean * size)/ (size - 1.0);
}
template <template<class T, class Allocator = std::allocator<T> > class Container>
double sd(Container<double> & x)
{
return std::sqrt(var(x));
}
int main()
{
std::vector<double> x;
x.push_back(1);
x.push_back(2);
x.push_back(3);
x.push_back(4);
std::list<double> y(x.begin(), x.end());
std::cout << mean(x) << std::endl;
std::cout << mean(y) << std::endl;
std::cout << var(x) << std::endl;
std::cout << var(y) << std::endl;
std::cout << sd(x) << std::endl;
std::cout << sd(y) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment