以下代码取自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