forked from edwardsjohnmartin/gvd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
statistics.h
94 lines (77 loc) · 2.14 KB
/
statistics.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*******************************************************
** Generalized Voronoi Diagram Project **
** Copyright (c) 2015 John Martin Edwards **
** Scientific Computing and Imaging Institute **
** 72 S Central Campus Drive, Room 3750 **
** Salt Lake City, UT 84112 **
** **
** For information about this project contact **
** John Edwards at **
** edwardsjohnmartin@gmail.com **
** or visit **
** sci.utah.edu/~jedwards/research/gvd/index.html **
*******************************************************/
#ifndef __STATISTICS_H__
#define __STATISTICS_H__
#include <iostream>
namespace oct {
/// /f$\sqrt{\frac{1}{N} \left(\sum_{i=1}^N x_i^2\right) - \overline{x}^2}/f$
/// is used to calculate the standard deviation.
///
/// No checks are made for overflow! This class should not be used for critical
/// calculations.
template <typename T>
class statistics
{
public:
statistics() : _N(0), _sum(0), _squares(0) {}
~statistics() {}
void operator()(T sample) {
add(sample);
}
void add(T sample)
{
if (_N == 0) {
_min = sample;
_max = sample;
}
++_N;
_sum += sample;
_squares += (sample * sample);
_min = (_min<sample)?_min:sample;
_max = (_max>sample)?_max:sample;
}
size_t N() const
{ return _N; }
T mean() const
{ return _sum / (T) _N; }
T variance() const
{
T avg = mean();
return _squares / (T) _N - avg * avg;
}
T std_dev() const
{ return sqrt(variance()); }
T min() const
{ return _min; }
T max() const
{ return _max; }
T range() const {
return _max - _min;
}
private:
size_t _N;
T _sum;
T _squares;
T _min;
T _max;
};
template <typename T>
std::ostream& operator<<(std::ostream& out, const statistics<T>& stats)
{
out << "Sample size = " << stats.N() << " Average = " << stats.mean() << " Standard deviation = " << stats.std_dev()
<< " Min = " << stats.min() << " Max = " << stats.max();
return out;
}
}
#endif