algorithm - Avoiding Possible Precision Loss with a Simple Moving Average -
suppose had basic moving average function keeping track of sum. example:
queue values; double sum; double calcsma(double next) { values.push(next); sum -= values.pop(); sum += next; return sum / sma_length; }
one example of how break down if our window 5 wide fed like: 2, 2, 2, 2, 2, 2, 2, 1e100, 2, 2, 2, 2, 2, 2, 2, 2
. output 2, 2, 2, 2e99, 2e99, 2e99, 2e99, 2e99, 0, 0, 0
.
even if sum isn't quite dramatically off, there still quite reasonable instances small loss in precision make sum artificially increase tiny amount. on long period of time, add , become issue.
does have ideas of how work around loss in precision?
edit: note function designed work o(1). necessary. so, recalculating each time won't work: window large.
you recalculate fresh sum on every sma_length values stop errors accumulating:
queue values; double sum = 0.0; double freshsum = 0.0; int count = 0; double calcsma(double next) { values.push(next); sum -= values.pop(); sum += next; freshsum += next; if(++count == sma_length) { sum = freshsum; freshsum = 0.0; count = 0; } return sum / sma_length; }
Comments
Post a Comment