使用整数算法的平滑算法

hel*_*ker 6 c c++ integer bit-manipulation arduino

以下代码取自Arduino平滑教程:

int smooth(int data, float filterVal, float smoothedVal) { 

  if (filterVal > 1) {
    filterVal = .99;
  }
  else if (filterVal <= 0) {
    filterVal = 0;
  }

  smoothedVal = (data * (1 - filterVal)) + (smoothedVal  *  filterVal);

  return (int)smoothedVal;
}
Run Code Online (Sandbox Code Playgroud)

以下声明来自同一个教程,让我思考:

如果您需要更高的速度或想要避免浮点数,可以使用全整数来轻松地重写此函数.

事实是我确实想避免浮动并提高速度,但我想知道:如何将其转换为整数运算?比特攻击解决方案是一个奖励; o)

mea*_*ers 3

一种简单的技术是通过将输入值乘以例如10000并将结果放入 an 中int,在 中进行计算int,然后float通过除以相同的因子将输出缩放回 a 。

在您的函数中,您还需要使用相同的因子来扩展所有内容。

因子的选择取决于值的可能范围;您希望避免高端溢出和低端不准确。如果你仔细想想,这个因素决定了你把小数点放在哪里:定点,而不是浮点。

该因子可以是任何东西,不一定是1001000、 等等,但627也可以。

如果您沿着这条路线走下去,您希望将尽可能多的代码转换为int,因为上述转换当然也需要时间。

为了说明我的观点,可以是以下内容:

#define FACTOR 10000  // Example value.
int smooth(int data, int filterVal, int smoothedVal)
{ 
    if (filterVal > FACTOR)
    {
        filterVal = FACTOR - 100;
    }
    else if (filterVal <= 0)
    {
        filterVal = 0;
    }

    smoothedVal = (data * (FACTOR - filterVal)) + (smoothedVal * filterVal);

    return smoothedVal;
}
Run Code Online (Sandbox Code Playgroud)

您可能需要/想要检查是否溢出,...