semf
average.cpp
Go to the documentation of this file.
1
11
12namespace semf
13{
14template <typename T>
15T Average<T>::value(const T data[], size_t dataSize)
16{
17 const Buffer<T> buffer(const_cast<T*>(data), dataSize);
18 return value(buffer);
19}
20
21template <typename T>
23{
24 T sumLow = 0;
25 T sumLowLast = 0;
26 size_t sumHigh = 0;
27 size_t sumHighLast = 0;
28 size_t nValuesSummed = 0;
29
30 if (data.data() == nullptr)
31 {
32 return 0;
33 }
34
35 // summing up the values
36 for (size_t i = 0; i < data.count(); i++)
37 {
38 sumLow += data[i];
39 if (sumLowLast > sumLow)
40 {
41 sumHigh++;
42
43 // prevent overflow from sumHigh
44 if (sumHighLast > sumHigh)
45 {
46 sumLow = sumLowLast;
47 sumHigh = sumHighLast;
48 break;
49 }
50 }
51 sumLowLast = sumLow;
52 sumHighLast = sumHigh;
53 nValuesSummed++;
54 }
55
56 return divide(sumHigh, sumLow, nValuesSummed);
57}
58
59template <typename T>
60T Average<T>::divide(size_t highValue, T lowValue, size_t divider)
61{
62 uint32_t binPlacesDivider = 0; // for counting the binary places of the divider
63 T mask = 0;
64 size_t divideHelper = 0; // for saving the intermediate steps by the division
65 T result = 0;
66
67 // counting the binaryplaces of the divider
68 for (uint32_t i = 0; i < static_cast<uint32_t>(sizeof(divider)) * 8; i++)
69 {
70 if (!(divider >> i))
71 {
72 binPlacesDivider = i;
73 break;
74 }
75 }
76 // Make a mask that has as many ones as the divider has binary places
77 for (uint32_t i = 0; i < binPlacesDivider; i++)
78 {
79 mask = mask << 1;
80 mask += 1;
81 }
82
83 divideHelper = highValue >> static_cast<T>(((sizeof(std::size_t) * 8) - binPlacesDivider) & mask);
84
85 // do division
86 for (int i = ((sizeof(T) + sizeof(std::size_t)) * 8) - binPlacesDivider; i >= 0; i--)
87 {
88 result <<= 1;
89 if (divideHelper >= divider)
90 {
91 result++;
92 divideHelper = divideHelper - divider;
93 }
94 divideHelper = divideHelper << 1;
95
96 if (i > static_cast<int>(sizeof(T)) * 8)
97 divideHelper = divideHelper + static_cast<T>((highValue >> (i - (sizeof(T) * 8) - 1)) & 1);
98 else
99 divideHelper = divideHelper + static_cast<T>((lowValue >> (i - 1)) & 1);
100 }
101 return result;
102}
103} /* namespace semf */
Average calculates the average value of the entries of a given Buffer or an data array....
Definition: average.h:25
static T value(const T data[], size_t dataSize)
Calculates an average out of an array.
Definition: average.cpp:15
Buffer is a base class for buffer implementations.
Definition: buffer.h:42
T * data() const
Returns the pointer to the first element of the data array.
Definition: buffer.h:139
virtual size_t count() const
Returns the number of entries stored in the buffer.
Definition: buffer.h:133