recursive average
double average = 0; int number_of_samples = 0; for(int i=0; i<v.size(); ++i) { number_of_samples++; average = (average * (number_of_samples - 1) + v[i]) / number_of_samples; };
The advantage is that the variable "average" will always keep a value that is roughly in the same order of magnitude as the elements that are being averaged. That should improve the resulting accuracy.
2 Comments:
seems like it would be useful if you were averaging a lot of large numbers where the sum of all items wouldn't fit in a double, and you don't have to do a really big division at the end.
i'm not sure what you mean re: accuracy?
It has to do with how floating point works, and I'm going to vulgarly misuse accuracy and precision I'm sure... But the idea is that instead of doing the usual where you sum everything and then divide at the end.. This way keeps the most amount of precision.
You only have so many significant digits of precision, and if you use them up by accumulating a huge number first, then the small bits on the end get lost. This way is supposed to avoid that by keeping things within the same magnitude of your final result. (At the cost of more divisions)
http://en.wikipedia.org/wiki/Double_precision
Post a Comment
<< Home