using 32bit floating point values, what's the best (numerically most accurate) way of computing the average if - when starting the computation - I don't know yet how many values I gonna have (in the following examples I just iterate over a vector so I would know the coult, but let's suppose I'd know the element count only in the end)?
I could do for example
float result = 0.f;
for(float num: numbers) {
result += num;
}
num /= numbers.size();
but as result grows larger, so does the precision. With small values, at some point result += num;
will not actually change result anymore.
I could do
float result = numbers[0]
for(int i=1, i<numbers.size(); i++) {
float frac = (i/float(i+1));
result = result * frac + numbers[i] * (1.0f-frac);
}
but it seems I'd apply a cummulative error to result that way.
Is there a better way without going to 64bit double?