I'm having a problem with the specific set of values in this code snippet.
double inputs[] = {0, -546543, 99015, 6750, 825, 2725, 70475,
50950, 42200, 6750, 26925, 16125, 134350, 10075, 79378};
double result = 0;
for (int i = 0; i < 15; i++) {
result += inputs[i]/100;
}
I expected the final value of result
to be 0. And if I take out the division by 100 it is. But when I divide each value by 100 before adding it to result
, I end up with -6.8212102632969618e-013 instead.
There's a lot I don't understand about floating point arithmetic. I know it's not guaranteed to be fully precise. But there doesn't seem to be anything unusual about this dataset—no very large or very small values—so I'm suprised that the calculation is coming out wrong.
Can anybody explain this to me, and offer any suggestions as to how to avoid this problem? The code I presented is simplified; in the actual code I can't just not divide by 100, and I can't very easily add the numbers as integers and divide them later.
Any suggestions will be appreciated.