在 C++ 中计算滚动/移动平均值
我知道这可以通过 boost 实现:
I know this is achievable with boost as per:
使用boost::accumulators,如何重置滚动窗口大小,是否保留额外的历史记录?
但我真的很想避免使用 boost.我已经用谷歌搜索过,但没有找到任何合适或可读的例子.
But I really would like to avoid using boost. I have googled and not found any suitable or readable examples.
基本上,我想使用最近的 1000 个数字作为数据样本来跟踪正在进行的浮点数流的移动平均值.
Basically I want to track the moving average of an ongoing stream of a stream of floating point numbers using the most recent 1000 numbers as a data sample.
实现这一目标的最简单方法是什么?
What is the easiest way to achieve this?
我尝试使用圆形阵列、指数移动平均线和更简单的移动平均线,发现圆形阵列的结果最适合我的需要.
I experimented with using a circular array, exponential moving average and a more simple moving average and found that the results from the circular array suited my needs best.
推荐答案
您只需要一个包含 1000 个元素的循环数组(循环缓冲区),您可以在其中将元素添加到前一个元素并存储它.
You simply need a circular array (circular buffer) of 1000 elements, where you add the element to the previous element and store it.
它变成了一个递增的和,你总是可以得到任意两对元素之间的和,然后除以它们之间的元素数,得到平均值.
It becomes an increasing sum, where you can always get the sum between any two pairs of elements, and divide by the number of elements between them, to yield the average.
相关文章