Bayley Wang
/
foc-ed_in_the_bot_compact
robot
Diff: Filter/CircularBuffer.cpp
- Revision:
- 148:9bca96f7be5c
- Parent:
- 147:c1b2379b8874
- Child:
- 149:c51c0258c923
--- a/Filter/CircularBuffer.cpp Wed May 03 13:27:12 2017 +0000 +++ b/Filter/CircularBuffer.cpp Wed May 03 13:59:51 2017 +0000 @@ -10,7 +10,7 @@ newest_index = -1; num = 0; sum = 0.0f; - + buf = (float*)malloc(_length * sizeof(float)); sorted = (float*)malloc(_length * sizeof(float)); for (int i = 0; i < _length; i++) { @@ -31,33 +31,32 @@ buf[newest_index] = x; sum += x; num++; - + if (!_use_median) return; - + /*insert x into sorted array*/ int i = num - 1; - while (i > 0 && sorted[i] > x) { + while (i > 0 && sorted[i - 1] > x) { sorted[i] = sorted[i - 1]; i--; } sorted[i] = x; - } - else { + } else { /*update circular buffer*/ float oldest = buf[oldest_index]; - + sum -= buf[oldest_index]; oldest_index++; if (oldest_index >= _length) oldest_index -= _length; - + newest_index++; if (newest_index >= _length) newest_index -= _length; buf[newest_index] = x; - + sum += x; - + if (!_use_median) return; - + /*find sorted index of oldest element*/ int removed; for (removed = 0; removed < _length; removed++) { @@ -68,34 +67,30 @@ int i; if (removed == _length - 1) { i = _length - 1; - while (i > 0 && sorted[i] > x) { + while (i > 0 && sorted[i - 1] > x) { sorted[i] = sorted[i - 1]; i--; } sorted[i] = x; - } - else if (removed == 0) { + } else if (removed == 0) { i = 0; - while (i < _length - 1 && sorted[i] < x) { + while (i < _length - 1 && sorted[i + 1] < x) { sorted[i] = sorted[i + 1]; i++; } sorted[i] = x; - } - else if (sorted[removed - 1] <= x && sorted[removed + 1] >= x) { + } else if (sorted[removed - 1] <= x && sorted[removed + 1] >= x) { sorted[removed] = x; - } - else if (sorted[removed - 1] > x) { + } else if (sorted[removed - 1] > x) { i = removed; - while (i > 0 && sorted[i] > x) { + while (i > 0 && sorted[i - 1] > x) { sorted[i] = sorted[i - 1]; i--; } sorted[i] = x; - } - else { + } else { i = removed; - while (i < _length - 1 && sorted[i] < x) { + while (i < _length - 1 && sorted[i + 1] < x) { sorted[i] = sorted[i + 1]; i++; } @@ -112,16 +107,14 @@ if (num < _length) { if (num % 2 == 1) { return sorted[(num - 1) / 2]; - } - else { + } else { return (sorted[num / 2] + sorted[num / 2 - 1]) / 2.0f; } } else { if (_length % 2 == 1) { return sorted[(_length - 1) / 2]; - } - else { + } else { return (sorted[_length / 2] + sorted[_length / 2 - 1]) / 2.0f; } }