change the condition on calculate prevN avg & rms

replace mag>avg+k*rms with fabs(mag-avg)>k*rms