libpromeki 1.0.0-alpha
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
statsaccumulator.h
Go to the documentation of this file.
1
8#pragma once
9
10
11#include <promeki/config.h>
12#if PROMEKI_ENABLE_CORE
13#include <cmath>
14#include <cstdint>
15#include <promeki/namespace.h>
16
17PROMEKI_NAMESPACE_BEGIN
18
49class StatsAccumulator {
50 public:
52 StatsAccumulator() = default;
53
58 void add(double value) {
59 if (_count == 0) {
60 _min = value;
61 _max = value;
62 } else {
63 if (value < _min) _min = value;
64 if (value > _max) _max = value;
65 }
66 _count++;
67 _sum += value;
68 _sumSq += value * value;
69 return;
70 }
71
76 void merge(const StatsAccumulator &other) {
77 if (other._count == 0) return;
78 if (_count == 0) {
79 _min = other._min;
80 _max = other._max;
81 } else {
82 if (other._min < _min) _min = other._min;
83 if (other._max > _max) _max = other._max;
84 }
85 _count += other._count;
86 _sum += other._sum;
87 _sumSq += other._sumSq;
88 return;
89 }
90
92 void reset() {
93 _count = 0;
94 _sum = 0.0;
95 _sumSq = 0.0;
96 _min = 0.0;
97 _max = 0.0;
98 return;
99 }
100
102 uint64_t count() const { return _count; }
103
105 bool isEmpty() const { return _count == 0; }
106
108 double sum() const { return _sum; }
109
111 double sumSq() const { return _sumSq; }
112
114 double min() const { return _min; }
115
117 double max() const { return _max; }
118
123 double mean() const {
124 if (_count == 0) return 0.0;
125 return _sum / static_cast<double>(_count);
126 }
127
132 double variance() const {
133 if (_count < 2) return 0.0;
134 double n = static_cast<double>(_count);
135 double v = (_sumSq - _sum * _sum / n) / (n - 1.0);
136 return v > 0.0 ? v : 0.0;
137 }
138
143 double stddev() const {
144 double v = variance();
145 return v > 0.0 ? std::sqrt(v) : 0.0;
146 }
147
148 private:
149 uint64_t _count = 0;
150 double _sum = 0.0;
151 double _sumSq = 0.0;
152 double _min = 0.0;
153 double _max = 0.0;
154};
155
156PROMEKI_NAMESPACE_END
157
158#endif // PROMEKI_ENABLE_CORE