Mail Archives: djgpp/1998/06/17/10:14:23
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 <float.h>.)
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.
- Raw text -