平滑算法采用整数算法
Smoothing algorithm using integer arithmetic
以下代码取自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;
}
下面这段话,摘自同一篇教程,引起了我的思考:
如果你需要更快的速度或想要避免浮点数,这个函数可以很容易地用全整数数学重写。
事实是我确实想避免浮点数并提高速度,但我想知道:如何将其转换为整数算术?敲位解决方案是额外的;0)
一种简单的技术是通过将输入值乘以例如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;
}
你可能需要/想要检查溢出,…
// ------------------------------------------------------------------
// SMOOTHING WITH INTEGER VARIABLES (CSHARP)
// ------------------------------------------------------------------
Int32 Storage;
Int32 SmoothingINT(Int32 NewValue, Int32 Divisor)
{
Int32 AvgValue;
// ------------------------- Compute the output averaged value
AvgValue = Storage / Divisor;
// ------------------------- Add to storage the delta (New - Old)
Storage += NewValue - AvgValue;
// -------------------------
return AvgValue;
}
或
' -------------------------------------------------------------------
' SMOOTHING WITH INTEGER VARIABLES (VbNet)
' -------------------------------------------------------------------
Function SmoothingINT(ByVal NewValue As Int32, ByVal Divisor Int32) As Int32
Dim AvgValue As Int32
Static Storage As Int32
' -------------------------- Compute the output averaged value
AvgValue = Storage Divisor
' -------------------------- Add to storage the delta (New - Old)
Storage += NewValue - AvgValue
' --------------------------
Return AvgValue
End Function
相关文章:
- 具有非整数边容量的最大流量的Dinic算法
- 如何使用 STL 算法将整数向量转换为字符串向量?
- 从整数向量向量搜索整数向量的最佳算法
- C 中俄罗斯农民算法中的整数溢出
- 在某些范围更新后获取整数数组的最终状态的有效算法是什么?
- 计算以毫秒为单位的分类算法对整数阵列排序的时间
- 用于在2个带符号整数区间之间进行除法的C++算法
- 一对整数的哈希算法
- 这种计算 32 位整数中设置位数的算法如何工作
- 非标准排序算法,用于随机独特整数
- 减少整数分数算法-解决方案说明
- 如何找到硬件算法完全支持的最大整数
- c++快速排序算法中500000排序整数数组的Seg错误
- 用于从包含最大求和的整数数组中提取子数组的算法
- 整数的快速排序算法
- 计算一组关系的整数映射的更有效的算法
- 运行整数数组所有组合的算法
- 为什么我的C++算法不能处理超过 62 位的整数?
- c++算法将一个整数转换为布尔数组
- 整数字符串压缩算法