This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Comparing doubles


dewar@gnat.com (Robert Dewar)  wrote on 07.07.02 in <20020707145355.AFF58F28D5@nile.gnat.com>:

> First, what do we mean by "answer is right". Well the standard does not
> define this. At one level, doing addition by complement followed by
> subtract is obviously wrong since it does not give proper IEEE minus
> zero semantics. At the other end, doing a subtraction *instead* of

That is "obvious" only if you have reason to expect IEEE minus zero  
semantics, which in a non-IEEE reals implementation you most certainly  
don't. Many of those don't even *have* the concept of "negative zero".

Your whole argument seems to be based on IEEE reals. Fine if that's what  
they're supposed to be, worthless otherwise.

If your reals do not have IEEE-style NaN or signed zero or stuff like  
that, I still see two problems with the proposed scheme.

Buut first, just to be clear what we are talking about, here is how I  
understand that scheme:

int double_equal(double a, double b)
{
        double c = a - b;     /*1*/
        float d = (float)c;   /*2*/
        return d == 0.0;      /*3*/
}

Line 1 has the problem that you can have an overflow. I.e., depending on  
the actual values of a and b, the result can be too large to be presented  
in a double. *If* you can catch that case and convert it to a "return 0",  
fine, otherwise you have a problem.

That subtraction can also underflow, if both a and b are already close to  
zero. If you have un-normalized doubles, you can still represent the  
result; if not, given that you are about to convert it into a float which  
certainly will not be able to represent a number that double can't, this  
means according to the proposed algorithm you should consider this case as  
"equal". The same comments about handling it apply as in the overflow  
case.

Line 2 obviously can again produce over- or underflow the same as line 1,  
with all the same arguments.

In any case, by the time you reach line 3, you have lost some bits from  
the result of the subtraction. If you do not have any under- or overflow,  
given that you are doing nothing more than check if you have zero, that is  
harmless.

So, the problematic cases are those where you will produce either overflow  
or underflow, either in the subtraction or in the truncate. Otherwise, the  
loss of precision does not seem problematic (or in other words, the result  
seems to be exact in the cases where it works at all).

MfG Kai


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]