Updated German translation
[dasher.git] / Src / DasherCore / GameStatistics.h
blob11a7656e060e0fa74883411b67dcbf49093ab8be
1 #ifndef __GameStatistics_h__
2 #define __GameStatistics_h__
4 // Code examples modified from C++ Cookbook O'Reilly.
5 // Code use falls under fair use as dicussed in the book
7 #include <numeric>
8 #include <cmath>
9 #include <algorithm>
10 #include <functional>
11 #include <vector>
13 template<class T>
14 T nthPower(T x, int n)
16 T ret = x;
17 for (int i=1; i < n; ++i)
18 ret*=x;
19 return ret;
22 template<class T>
23 struct SumDiffNthPower
25 SumDiffNthPower(T x, int n) : m_mean(x), m_n(n) {}
26 T operator()(T sum, T current)
28 return sum+nthPower(current-m_mean, m_n);
30 T m_mean;
31 int m_n;
34 template<class T, class Iter_T>
35 T nthMoment(int n, Iter_T first, Iter_T last, T mean)
37 size_t cnt = last - first;
38 return std::accumulate(first, last, T(), SumDiffNthPower<T>(mean, n))/cnt;
40 template<typename T>
41 std::string ComputeStats(const std::vector<T> &v)
43 if (v.empty()) return "";
45 double m1 = nthMoment(1,v.begin(), v.end(), 0.0);
46 double m2 = nthMoment(2,v.begin(), v.end(), m1);
47 double m3 = nthMoment(3,v.begin(), v.end(), m1);
48 double m4 = nthMoment(4,v.begin(), v.end(), m1);
50 double dev = sqrt(m2); // Standard Deviation
51 double skew = m3/(m2*dev); // Skewness
52 double kurt = m4 / (m2*m2) - 3.0; // Excess Kurtosis
54 ostringstream m_Statsbreakdown("");
55 #define SEP " "
56 m_Statsbreakdown << "Samples: " << v.size() << SEP
57 << "Mean: " << m1 << SEP
58 << "StdDev: " << dev << SEP
59 << "Skew: " << skew << SEP
60 << "Kurt: " << kurt << SEP;
61 #undef SEP
62 return m_Statsbreakdown.str();
65 template<class A, class B, class T>
66 struct MemberSumDiffNthPower
68 MemberSumDiffNthPower(A T::* pm, B x, int n) : m_mean(x), m_pm(pm), m_n(n) {}
69 B operator()(B sum, T current)
71 return sum+nthPower(current.*m_pm-m_mean, m_n);
73 B m_mean;
74 A T::* m_pm;
75 int m_n;
78 template<class T, class Iter_T, class A, class B>
79 B MemberNthMoment(int n, Iter_T first, Iter_T last, A T::* pmember, B mean)
81 size_t cnt = last - first;
82 return std::accumulate(first, last, B(), MemberSumDiffNthPower<A,B,T>(pmember,mean,n))/cnt;
85 #endif