math.h Source File

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
math.h
Go to the documentation of this file.
1 #ifndef OSL_MISC_MATH_H
2 #define OSL_MISC_MATH_H
3
4 #include <numeric>
5 #include <cmath>
6 #include <algorithm>
7 #include <functional>
8
9 namespace osl
10 {
11 namespace misc
12 {
16 template<unsigned int N, class T>
17 T nthPower(T x)
18 {
19 if (N==0)
20 return 1;
21
22 const T temp = nthPower<N/2>(x);
23 if (N%2 == 0)
24 return temp * temp;
25 else
26 return temp * temp * x;
27 }
28
29 template<class T, int N>
30 struct SumDiffNthPower
31 {
32 T mean;
33 SumDiffNthPower(T mean) : mean(mean) {}
34 T operator()(T sum, T current)
35 {
36 return sum + nthPower<N>(current - mean);
37 }
38 };
39
40 template<class T, int N, class Iter_T>
41 T nthMoment(Iter_T first, Iter_T last, T mean)
42 {
43 const size_t cnt = distance(first, last);
44 return accumulate(first, last, T(), SumDiffNthPower<T, N>(mean))/cnt;
45 }
46
47 template<class T, class Iter_T>
48 T computeVariance(Iter_T first, Iter_T last, T mean)
49 {
50 return nthMoment<T, 2>(first, last, mean);
51 }
52
53 template<class T, class Iter_T>
54 T computeStdDev(Iter_T first, Iter_T last, T mean)
55 {
56 return sqrt(computeVariance(first, last, mean));
57 }
58
59 template<class T, class Iter_T>
60 T computeSkew(Iter_T first, Iter_T last, T mean)
61 {
62 const T m3 = nthMoment<T, 3>(first, last, mean);
63 const T m2 = nthMoment<T, 2>(first, last, mean);
64 return m3 / (m2 * sqrt(m2));
65 }
66
67 template<class T, class Iter_T>
68 T computeKurtosisExcess(Iter_T first, Iter_T last, T mean)
69 {
70 const T m4 = nthMoment<T, 4>(first, last, mean);
71 const T m2 = nthMoment<T, 2>(first, last, mean);
72 return m4 / (m2 * m2) - 3;
73 }
74
75 template<class T, class Iter_T>
76 void computeStats(Iter_T first, Iter_T last,
77 T& sum, T& mean, T&var, T&std_dev, T& skew, T& kurt)
78 {
79 const size_t cnt = distance(first, last);
80 sum = accumulate(first, last, T());
81 mean = sum / cnt;
82 var = computeVariance(first, last, mean);
83 std_dev = sqrt(var);
84 skew = computeSkew(first, last, mean);
85 kurt = computeKurtosisExcess(first, last, mean);
86 }
87 }
88 }
89 #endif /* _MISC_MATH_H */
90 // ;;; Local Variables:
91 // ;;; mode:c++
92 // ;;; c-basic-offset:2
93 // ;;; End: