bug-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Comparing a double against 0


From: Michael D. Berger & Rosalie A. Clavez
Subject: Re: Comparing a double against 0
Date: Wed, 02 Jul 2003 19:16:00 -0400

Julian,

Perhaps it is not what you want, but it is not really a bug.
Because of the nature of the representations and computations
involving floating point numbers, exact comparisons are rarely
appropriate for float or double.  The way to check for zero is
something like:

   double       tolerance = 0.0000001;
   double       myResult = doMyComputation();
   if (fabs(myResult) < tolerance) /* If I got the function name right */
        doSomethingForZero(); /* Close enough. */

If this will not serve your purpose, then you should not be
using float or double.

Regards,
Mike.

Julián Albo wrote:
> 
> Hello.
> 
> I have the following program:
> 
> #include <stdio.h>
> #include <math.h>
> 
> const double zero= 0.0;
> 
> int main ()
> {
>         double a= -1.0e-120;
>         if (a < zero)
>                 printf ("%g < 0\n", a);
>         if (a > zero)
>                 printf ("%g > 0\n", a);
>         if (a == zero)
>                 printf ("%g == 0\n", a);
> }
> 
> Compiled as C++ with gcc version 3.3 20030226 (prerelease) (SuSE Linux)
> 
> The ouput is -1e-120 == 0.
> 
> Dropping the const in zero the output is: -1e-120 < 0, as expected.
> 
> Compiled as C program the result is correct with and without const.
> 
> Using the literal 0.0 instead of the zero variable, the result is wrong
> with C++ and correct with C.
> 
> Is this a known bug?
> 
> Regards.
> 
> _______________________________________________
> Bug-gplusplus mailing list
> address@hidden
> http://mail.gnu.org/mailman/listinfo/bug-gplusplus

-- 
Michael D. Berger
address@hidden




reply via email to

[Prev in Thread] Current Thread [Next in Thread]