What is the most accurate way to calculate the sum of vector elements using std :: accumulate?

Possible duplicate:
Question about C ++ anti-aliasing accuracy

I had the problem of determining the most accurate method out of three in order to calculate the sum of vector elements that can only be positive numbers using std :: accumulate.

1)

double sum(vector<float> &v) { return accumulate(v.begin(), v.end(), 0.0); } 

2)

 double sum(vector<float> &v) { sort(v.begin(), v.end()); return accumulate(v.begin(), v.end(), 0.0); } 

3)

 double sum(vector<float> &v) { sort(v.begin(), v.end(), greater<float>()); return accumulate(v.begin(), v.end(), 0.0); } 

This is a kind of job interview question, so I got these three ways to calculate the amount. I searched a lot on the Internet, but could not understand the difference. Could you help me guys understand this?

+4
source share
1 answer

The difference should be very small, but starting with smaller numbers will be a little more accurate. Consider, for purposes of presentation, that your floating point number contains only 4 significant digits and a metric, and that it was decimal, not binary. Using numbers:

 a = 5000 b = 5000 c = 1000e4 (10000000) 

If we add c first, then either a or b , then the smaller one will fall from the view and be rounded. The final result c + b + a will give 1000e4 . If, on the other hand, we add a and b , we first get 1e4 as the first intermediate value, and adding that 1001e4 will be 1001e4 to c , which is a more accurate result for the operation.

+4
source

All Articles