Originally Posted by

**mccoz**
Hi there!

I have a problem with an algorithm I wrote: I must use double representation for the values but different sequences of arithmetic operations which are supposed to result in equal numbers are delivering slightly different numbers, e.g. 4*10^(-12) difference. This is definitely due to the binary representation of the numbers but is it somehow possible to circumvent these problems?

For instance:

-1629.000+1629.000 = -4.3200998334214e-012

Right now I am using a lot of rounding to decimal places but there are still some points I am missing. Is there another way to generally prevent these problems?

Thanks a lot for considering my question!!!

--mccoz

If you have data values (or intermediate products in your calculations) that cannot be represented exactly as a floating point number in whatever system you are using, you can't guarantee that roundoff error can be circumvented.

Now as to your example, it turns out that 1269.000 and -1269.000 are exactly representable as floating point numbers in every C compiler that I have access to, so there will be no rounding error.

try this

Code:

#include <stdio.h>
int main()
{
double x, y, z;
x = -1269.000;
y = 1269.000;
z = x + y;
printf("x = %.20e, y = %.20e\nz = %.20e\n", x, y, z);
return 0;
}

I would like to know if you get anything other than

z = 0.00000000000000000000e+00

I hate to repeat myself, but if the data items and all intermediate terms in the calculations are exactly representable as floats (or doubles), you won't have round-off errors.

maybe the following shows how people can be confused by printouts:

Code:

#include <stdio.h>
int main()
{
double x, y, z;
x = -1269.0000000002;
y = 1269.0000000003;
z = x + y;
printf("With default precision output format, roundoff error is puzzling:\n");
printf("x = %e, y = %e, z = %e\n", x, y, z);
printf("\n\n");
printf("But if you print more significant digits, it makes more sense:\n");
printf("x = %.20e, y = %.20e\nz = %.20e\n", x, y, z);
return 0;
}

The first printf() shows apparent roundoff error in the addition, but actually the values being added don't have a zero sum. This is shown by the second printf()

Regards,

Dave