Date: Wed, 17 Jun 1998 17:13:42 +0300 (IDT) From: Eli Zaretskii To: Roberto Sassi cc: djgpp AT delorie DOT com Subject: Re: A question about atof() and the double 0.1 In-Reply-To: <3587a411.12016463@news.polimi.it> Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII Precedence: bulk On Wed, 17 Jun 1998, Roberto Sassi wrote: > r= (double) atof(rr); > if(r==((double)0.1)) printf("OKAY\n"); > else printf("ERROR\n"); [snip] > OKAY > 0.10000000000000000555111512312578270212 > ERROR > OKAY > 0.25000000000000000000000000000000000000 > > As you can see, with the number 0.25, there is no problem. The explanation is below, but I suggest to forget it immediately after reading and only remember the following Golden Rule Of Comparing Floating-Point Numbers: To check whether two floating-point numbers a and b are equal, use the following paradigm: if (fabs (a - b) > min (fabs(a), fabs(b))*DBL_EPSILON) printf ("Not equal\n"); else printf ("Equal\n"); (Use FLT_EPSILON for floats, LDBL_EPSILON for long doubles; all of them are defined on .) In other words, don't EVER compare FP numbers for exact equality, since floating-point computations have inherent inaccuracy, unlike integer numbers. And now for the explanation: 0.1 doesn't have an exact representation in most floating-point arithmetic systems, whereas 0.25 does (the latter is an integer power of 2, while the former isn't). So conversion of 0.25 to internal representation is exact, while that of 0.1 introduces small inaccuracies.