Lii Lii - 10 months ago 50
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");}

And the result I get is:

not equal

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?


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) {