SQLite Forum

Best way to observe database operations
Login
The algorithm is called "Successive Approximation to the Mean" and is one of the few accurate ways to calculate a floating point average that does not have the significant pathological behaviours associated with the schoolboy sum/count method.

let x be the sample,  
let n be the count of samples,  
let m be the current approximation to the mean (average)  

then, for the first sample  
m = x  
n = 1  

for each new sample to be incorporated in the mean  
n = n + 1  
m = m + ((x - m) / n)  

for each prior sample to be removed from the mean  
n = n - 1  
m = m - ((x - m) / n)  


Step 1:  x is 1:  
n = 1  
m = x = 1  

Step 2:  x is 2  
n = n + 1 = 1 + 1 = 2  
m = m + ((x - m) / n) = 1 + (1 / 2) = 1.5  

Step 3:  x is 3  
n = n + 1 = 2 + 1 = 3  
m = m + ((x - m) / n) = 1.5 + ((3 - 1.5) / 3) = 1.5 + (1.5 / 3) = 1.5 + 0.5 = 2  

Step 4:  x is 4  
n = n + 1 = 3 + 1 = 4  
m = m + ((x - m) / n) = 2 + ((4 - 2) / 4) = 2 + (2 / 4) = 2 + 0.5 = 2.5  


You can compute most statistical functions using running computations as well, including the various Means (arithmetic, absolute, RMS, logrithmic, etc), Kurtosis, Skew, Variance, and Standard Deviation, and probably more.  (Though except for the arithmetic mean/average, the only the intermediates are "running", you need to do a final calculation to get the actual final result from those intermediates whenever you need it).