简单移动平均值求和/偏移问题

时间:2013-04-22 19:50:41

标签: algorithm basic moving-average embedded-control

我写了一个简单的移动平均线,其温度移动窗口读作0到10V之间的电压。

该算法似乎工作正常,但是,它存在一个问题,即根据首先填充窗口的温度,移动平均值将具有不接近此值的任何值的偏移量。例如,使用temp运行此程序。插入室温的传感器产生4.4V或21.3C。但是,如果我拔掉温度。传感器电压降至1.4V,移动平均值保持在1.6V。随着窗口大小的增加,此偏移量变小。即使对于小窗口尺寸,如何移除此偏移量,例如。 20?

REM SMA Num Must be greater than 1
#DEFINE SMANUM 20
PROGRAM
'Program 3 - Simple Moving Average Test
CLEAR
DIM SA(1)
DIM SA0(SMANUM) : REM Moving Average Window as Array
DIM LV1
DIM SV2
LV0 = 0 : REM Counter
SV0 = 0 : REM Average
SV1 = 0 : REM Sum
WHILE(1)
    SA0(LV0 MOD SMANUM) = PLPROBETEMP : REM add Temperature to head of window
    SV1 = SV1 + SA0(LV0 MOD SMANUM) : REM add new value to sum
    IF(LV0 >= (SMANUM)) : REM check if we have min num of values
        SV1 = SV1 - SA0((LV0+1) MOD SMANUM) : REM remove oldest value from sum
        SV0 = SV1 / SMANUM : REM calc moving average
        PRINT "Avg: " ; SV0 , " Converted: " ; SV0 * 21.875 - 75
    ENDIF
    LV0 = LV0 + 1 : REM increment counter
WEND
ENDP

(注意这是由Parker以ACROBASIC为ACR9000编写的)

输出 - 附加温度传感器

Raw: 4.43115    Avg: 4.41926     Converted: 21.6713125
Raw: 4.43115    Avg: 4.41938     Converted: 21.6739375
Raw: 4.43359    Avg: 4.41963     Converted: 21.67940625
Raw: 4.43359    Avg: 4.41987     Converted: 21.68465625
Raw: 4.43359    Avg: 4.42012     Converted: 21.690125
Raw: 4.43359    Avg: 4.42036     Converted: 21.695375
Raw: 4.43359    Avg: 4.42061     Converted: 21.70084375

...在程序运行时删除温度传感器

Raw: 1.40625    Avg: 1.55712     Converted: -40.938
Raw: 1.40381    Avg: 1.55700     Converted: -40.940625
Raw: 1.40625    Avg: 1.55699     Converted: -40.94084375
Raw: 1.40625    Avg: 1.55699     Converted: -40.94084375
Raw: 1.40381    Avg: 1.55686     Converted: -40.9436875
Raw: 1.40381    Avg: 1.55674     Converted: -40.9463125
Raw: 1.40625    Avg: 1.55661     Converted: -40.94915625

移除传感器后,原始平均值和移动平均值之间会出现明显的偏移。

偏移也以相反的顺序发生:

输出 - 开始删除温度传感器的程序

Raw: 1.40381    Avg: 1.40550     Converted: -44.2546875
Raw: 1.40625    Avg: 1.40550     Converted: -44.2546875
Raw: 1.40625    Avg: 1.40549     Converted: -44.25490625
Raw: 1.40625    Avg: 1.40549     Converted: -44.25490625
Raw: 1.40625    Avg: 1.40548     Converted: -44.255125
Raw: 1.40625    Avg: 1.40548     Converted: -44.255125

...在程序运行时附加温度传感器

Raw: 4.43848    Avg: 4.28554     Converted: 18.7461875
Raw: 4.43848    Avg: 4.28554     Converted: 18.7461875
Raw: 4.43848    Avg: 4.28554     Converted: 18.7461875
Raw: 4.43848    Avg: 4.28554     Converted: 18.7461875
Raw: 4.43848    Avg: 4.28554     Converted: 18.7461875
Raw: 4.43359    Avg: 4.28530     Converted: 18.7409375

在连接传感器后,原始和移动平均值之间再次出现明显的偏移。

1 个答案:

答案 0 :(得分:1)

问题似乎是从总和中减去的值实际上并不是数组中最旧的值 - 实际上,最旧的值是由{{第一行中的新值覆盖的。 1}}循环。这是从总和中减去的第二个最老的值。

根据OP的建议,EDIT将Average和Sum变量更改为64位浮点,以解决随时间推移的精度损失。

确保首先减去最旧的值(一旦数组已满),给出预期的答案:

WHILE

我没有运行的BASIC环境,但是我在Python中测试了这个,并且对于与您的版本等效的代码和与我上面插入的版本相当的代码的预期输出得到了相同的错误输出。