데이터들이 계속 들어올 때마다 평균을 갱신하는 AverageFilter 소스 

 

데이터의 수와 이전 평균만 전역 변수나 static 변수로 저장해도 되지만

구조체로 만들어보았다.

#include <stdio.h>

typedef struct 
{
    int dataCnt;
    float preAvg;
    float nowAvg;
}Avg;

float avgFilter(Avg *Avg,int data){
    if(Avg->dataCnt==0){
        Avg->dataCnt++;
        Avg->nowAvg=data;
        Avg->preAvg=data;
        return Avg->nowAvg;
    }
    Avg->preAvg=Avg->nowAvg;
    Avg->dataCnt++;
    Avg->nowAvg=(1 - (float)1/(Avg->dataCnt))*(Avg->preAvg)+((float)1/Avg->dataCnt)*data;
    return Avg->nowAvg;
}

int main(){
    Avg avg;
    avg.dataCnt = 0;
    avg.nowAvg = 0;
    avg.preAvg = 0;

    printf("%f\r\n", avgFilter(&avg,10));
    printf("%f\r\n", avgFilter(&avg,20));
    printf("%f\r\n", avgFilter(&avg,30));
    printf("%f\r\n", avgFilter(&avg,40));
    printf("%f\r\n", avgFilter(&avg,50));
    printf("%f\r\n", avgFilter(&avg,60));
    printf("%f %f\r\n",avg.preAvg,avg.nowAvg);
}

반응형

+ Recent posts