How to compute the average of doubles, so that the total error is minimal?

Viewed 1653

Assume we have a long array of doubles, say, N == 1000000.

array<double, N> arr;

There are two naive approaches to compute the average. First

double result = 0;
for (double x : arr) {
    result += x;
}
result /= arr.size();

This may be inaccurate when the sum of values is very big. Floating point numbers lose precision then.

Another approach is:

double result = 0;
for (double x : arr) {
    result += x / arr.size();
}

This may lose precision when the numbers are small.

Is there any fail-safe way to calculate a simple average of floating point numbers? Solutions, which use only the standard library are appreciated.

3 Answers
Related