滑动平均滤波方法
功能:可以有效的消除电网附近伺服产生的高频干扰信号
输入数据类型为double 可以更具项目更改 滑动窗口越小处理速度越快,但对干扰的消除能力就会差点儿 所以需要更具现场干扰情况调整合适的窗口值
/// <summary>
/// 滑动平均滤波
/// </summary>
/// <param name="data">输入数据</param>
/// <param name="span">滑动窗口</param>
/// <returns></returns>
public double[] MovingAverage(double[] data, int span)
{
int b = 0;
if (span % 2 == 1)
b = (span - 1) / 2;
else
{
span -= 1;
b = (span - 1) / 2;
}
double[] smoothArray = new double[data.Length];
if (data.Length > span)
{
for (int i = 0; i < data.Length; i++)
{
if (i < b)
{
smoothArray[i] = 0;
for (int j = -i; j < i + 1; j++)
{
smoothArray[i] += data[i + j];
}
smoothArray[i] /= (2 * i + 1);
}
else if (i >= b && (data.Length - i) > b)
{
smoothArray[i] = 0;
for (int j = -b; j < b + 1; j++)
{
smoothArray[i] += data[i + j];
}
smoothArray[i] /= span;
}
else
{
smoothArray[i] = 0;
int c = data.Length - i - 1;
for (int j = -c; j < c + 1; j++)
{
smoothArray[i] += data[i + j];
}
smoothArray[i] /= (2 * c + 1);
}
}
}
else
{
throw new ArgumentException("span is bigger than data's count");
}
return smoothArray;
}