c - 在不使用数组或动态分配的情况下平滑输入数据

标签 c signal-processing moving-average

我试图在不使用数组或动态分配的情况下平滑输入数据(真正的正数)。可能吗?

结束条件是用户输入负数。例如:

 input: 1 2 3 4 5 -1
output: 1.5 2 3 4 4.5 

最佳答案

您可以使用移动平均线来做到这一点。最简单的形式

const int smooth_factor = 3; // the higher the value the more smooth it is.
int samples = 0;
int total = 0;         // make long or long long if danger of overflow.

int smoothed(int new_sample)
{
   if (samples == smooth_factor)
   {
      total -= total / smooth_factor;
      samples -= 1;
   }
   total += new_sample;
   samples += 1;
   return total / samples;
}

在实践中,您可能会通过使用 2 的幂 smooth_factor 并使用移位操作而不是除以 smooth_factor 来提高效率。 如果您愿意预播 total 和 num 个样本,您也可以去掉 if 语句。

const int smooth_factor = 16; // the higher the value the more smooth it is.
int total = 129;              // e.g. 129 = sum of first 16 samples

int smoothed(int new_sample)
{
      total -= total >> 4;
      total += new_sample;
      return total >> 4;
}

如果您要对多个值进行平滑处理,那么您可以删除其中一个变化而不会产生显着影响(但我将把它留作练习)。

关于c - 在不使用数组或动态分配的情况下平滑输入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13417711/

相关文章:

python - SciPy "lfilter"仅返回 NaN

python - 这是计算移动平均线的有效方法吗?

c - 如何从 vb6 调用 native C DLL

c - 如何访问结构的3维指针内的指针数组

c - tmpfile_s 中限制的目的是什么?

c - 与版本化字符串数据一起工作的数据结构?

c - 时域重叠相加如何实现时间拉伸(stretch)?

audio - 为什么stft(istft(x))≠x?

python - 如何确定 Python 中数字列表的趋势

mysql - 更新查询取决于前一行的值