Lii Lii - 2 months ago 8
C Question

C: imprecision in arithmetic of double

I have the following C code:

int main()
{
double a=.1,b=.2,c=.3,d=.4;
double e=a+b+c;
if (d- (1-e)){printf("not equal\n");}
printf("%.20f\n",d-(1-e));
}


And the result I get is:

not equal
0.00000000000000011102


I know this is due to the imprecision induced from the way computer saves a double. Is there a way to solve this, and make d-(1-e) equal to 0?

Answer

As PRP correctly suggests: you need to set a small number to use as zero. The standard C-library (Annex F in the C-standard) offers some macros in float.h for that purpose. You can use them like e.g.:

#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>

int main()
{
  double a = .1, b = .2, c = .3, d = .4;
  double e = a + b + c;
  if (d - (1 - e)) {
    printf("not equal\n");
  }
  printf("%.20f\n", d - (1 - e));
  printf("%.20f\n", DBL_EPSILON);
  if (fabs(d - (1 - e)) <= DBL_EPSILON) {
    printf("equal\n");
  }
  exit(EXIT_SUCCESS);
}