www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/06/17/10:14:23

Date: Wed, 17 Jun 1998 17:13:42 +0300 (IDT)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
To: Roberto Sassi <sassi AT biomed DOT polimi DOT it>
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: <Pine.SUN.3.91.980617170255.20468H-100000@is>
MIME-Version: 1.0

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 -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019