c++ - 使用整数运算的平滑算法

标签 c++ c arduino integer bit-manipulation

以下代码取自 Arduino tutorial on smoothing :

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;
}

以下摘自同一教程的声明让我开始思考:

This function can easily be rewritten with all-integer math, if you need more speed or want to avoid floats.

事实上我确实想避免 float 并提高速度,但我想知道:如何将其转换为整数运算? Bit-banging 解决方案是一种奖励;o)

最佳答案

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

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

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

因子可以是任何东西,不一定是100 , 1000 , 等等,但是 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;
}

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

关于c++ - 使用整数运算的平滑算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31707629/

相关文章:

c++ - 未插入 Windows API 组合框数据

c - 来自链接目录的 get_cwd()

android - 从android终端向蓝牙模块发送数据

c++ - 运行 Ubuntu Eclipse C++ Helloworld

c++ - Sqlite:如何从 C++ 绑定(bind)和插入日期?

c++ - 用于主机和设备代码的 CUDA 和 C++

iphone - 将 Biginteger 转换为 Bytearray(原始数据)

c - C 中的 Telegram 客户端

android - Arduino + 安卓 : How to switch activity

c++ - Arduino 打开 SD 文件名作为字符串