Created
February 10, 2014 07:09
-
-
Save denkiwakame/8911609 to your computer and use it in GitHub Desktop.
mean, variance, standard dev
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 <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