以下代码摘自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;
}从同一篇教程中摘录的以下陈述让我思考:
如果您需要更快的速度或想要避免浮动,这个函数可以很容易地用全整数的数学重写。
事实上,我确实想避免浮点,提高速度,但我想知道:如何将其转换为整数算法?比特敲击解决方案是一个额外的好处;o)
发布于 2015-07-29 18:28:41
一种简单的技术是将输入值与例如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;
}你可能需要/想检查是否溢出,.
发布于 2022-01-22 14:27:05
// ------------------------------------------------------------------
// 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 Functionhttps://stackoverflow.com/questions/31707629
复制相似问题