Possible loss of precision due the type-folding from
float
to int
26float foo(float a[100]) {
27 // Possible loss of precision due the type-folding from `float` to `int`".
28 // Replace last argument with 0.0
29 return std::accumulate(a, a + 99, 0);30}
Description
std::accumulate
folds the elements to the initial value type (provided as the last argument to std::accumulate
). When the initial value type is narrower than that of the elements to sum, there is a loss in precision.
Bad practice
// Loss due to truncation
a = {0.1f, 0.2f, 0.3f}
std::accumulate(begin(a), end(a), 0);
// Loss due to overflow
a = {65536LL * 65536 * 65536};
std::accumulate(begin(a), end(a), 0);
Recommanded
a = {0.1f, 0.2f, 0.3f}
accumulate(begin(a), end(a), 0.0);
OR
a = {0.1f, 0.2f, 0.3f}
accumulate<vector<float>::iterator, float>(begin(a), end(a), 0);