i'm studying for an exam and i tackled this problem
to add 0.1+0.2+...+1.00 ..or.. 1.00+0.99+0.98+...+0.1
in which order to add the numbers to get higher accuracy in Java?
i'm studying for an exam and i tackled this problem
to add 0.1+0.2+...+1.00 ..or.. 1.00+0.99+0.98+...+0.1
in which order to add the numbers to get higher accuracy in Java?
Any COBOL programmer would be able to answer this immediately.
The point of the question is that if you add the big numbers first, you lose precision when you come to add the small numbers. Add the small numbers first.
There is a result stating that one can get a better worst-case error bound if one adds a sequence of positive numbers in increasing order. This result does not imply that, for a given sequence of positive numbers, one gets smaller error by adding the numbers in increasing order.
Case in point:
int main() {
float f = 0, g = 1;
for (int i = 1; i <= 99; i++) {
char buf[42];
float ff;
sprintf(buf, "0.%02i", i);
sscanf(buf, "%f", &ff);
f += ff;
sprintf(buf, "0.%02i", 100-i);
sscanf(buf, "%f", &ff);
g += ff;
}
f += 1;
printf("%a %a\n", f, g);
}
prints
0x1.940002p+5 0x1.93fffep+5
The exact sum of the 100 float
s in question, which can be computed by declaring f
and g
as double
(but leaving ff
as a float
), is 0x1.93ffffff8p+5
, indicating that summing the numbers in decreasing order wins here.
Since this is an arithmetic series, its sum can be calculated as follows
Sn = n * (a1 + an) / 2
Sn ... sum
n ... number of elements
a1 ... first element
an ... last element
As you eliminate most of the numbers, this would seem the best solution.
Better than summing all the numbers linearly, you should study a divide and conquer method (sum half the array separately).
This is very much like Precise sum of floating point numbers