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.
Why not? That sounds like exactly the solution to your problem. Adding integers and dividing once is likely to much faster than adding floating-point numbers and dividing so much, too.
You are just accumulating error every time you divide by 100 (since 100 is not power of 2). All of your numbers are exactly representable in a
double, but when you divide them, they aren’t – hence your error. There’s not really anything you can do about it except modify your algorithm.In your case, since you’re dividing by 100, you could round off the final sum to the nearest 100th, and get the right result.