Precision sum of doubles Summing doubles can cause a loss of precision.
Summing integers, however, doesn't. (Assuming no overflow.)

Here's a high precision sum function I wrote:

#include &lt;iostream&gt;
#include &lt;vector&gt;
#include &lt;cmath&gt;
#define BASE 10

bool is_int(double n) {
  double intpart;
  return std::modf(n, &amp;intpart) == 0.0;
}

double sum(std::vector&lt;double&gt; nums) {
  int n = nums.size();

  int maxepower = 1;
  for (int i = 0; i &lt; n; ++i) {
    while(!is_int(nums[i] * pow(BASE, maxepower))) { maxepower++; }
  }

  int pieces[n];
  for (int i = 0; i &lt; n; ++i) {
    pieces[i] = nums[i] * pow(BASE, maxepower);
  }

  int sum = 0;
  for (int i = 0; i &lt; n; ++i) {
    sum += pieces[i];
  }

  return sum / pow(BASE, maxepower);
}


I'm new to C++ so extra feedback on idioms would be helpful.

EDIT:
Example:

int main() {
  std::cout &lt;&lt; 0.1 + 0.2 - 0.3 &lt;&lt; std::endl;
  std::cout &lt;&lt; sum({0.1, 0.2, -0.3}) &lt;&lt; std::endl;
}


gives

5.55112e-17
0
It has a bug: very small numbers are completely ignored:

sum({0.1, 0.0000001}) -&gt; 0.1


If technical limitations do not allow you to change this behaviour, you should:


Document it in a comment as a know limitation
Put a condition in the loop if x &lt; min_tolerance {fail}, to adhere to fail fast fail loudly, instead of silently failing.