-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstdev.h
38 lines (34 loc) · 1.03 KB
/
stdev.h
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
36
37
38
// https://stackoverflow.com/a/51823578/730033
#ifndef STD_DEV_H
#define STD_DEV_H
#include <vector>
#include <numeric>
#include <cmath>
#include <iostream>
const size_t MAX_ELEMENTS_TO_PRINT = 5;
double vec_mean(std::vector<double> const &vec)
{
return std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size();
}
double vec_stddev(std::vector<double> const &vec)
{
double mean = vec_mean(vec);
double sq_sum = std::inner_product(
vec.begin(), vec.end(), vec.begin(), 0.0,
[](double const &x, double const &y)
{ return x + y; },
[mean](double const &x, double const &y)
{ return (x - mean) * (y - mean); });
return std::sqrt(sq_sum / vec.size());
}
void vec_print(std::vector<double> const &vec)
{
std::cout << "values = [";
for (size_t i = 0; i < std::min(MAX_ELEMENTS_TO_PRINT, vec.size()); i++)
{
std::cout << vec[i] << ", ";
}
std::cout << "...] size: " << vec.size() << "\n";
std::cout << "mean: " << vec_mean(vec) << " ± " << vec_stddev(vec) << "\n";
}
#endif