Re: comparing doubles for equality



Richard Weeks <rweeks@xxxxxxxxxx> wrote:
After some hair pulling over the issue of comparing doubles for
equality, I came up with this solution based on the notion of
relative difference. I'd appreciate your comments.

#define MAXRELDIFF .000000000001

/* compare doubles for equality. First compare
integer parts; if they are unequal, return
false. If they are equal, calculate relative
difference of fractional parts and compare
it to a tolerance. */
int dbl_isequal(double a, double b)
{
double fraca, fracb, reldiff;

if((int)a == (int)b)

This probably will fail for numbers that can't be represented as
integers, e.g. for numbers like the numbers in the order of the
number of particles in one Mol of a substance which is ca. 6e23
and probably not an uncommon number in scientific calculations.
But on many systems such a number (or just the national debt of
some countries;-) won't fit into an int (or even a long int)

{
fraca = a - (int)a;
fracb = b - (int)b;
reldiff = rel_diff(fraca, fracb);
if(reldiff > MAXRELDIFF) return 0;
else return 1;

You could write that also as

return reldiff <= MAXRELDIFF;

}
return 0;
}

double rel_diff(double a, double b)
{
double c, d;
c = fabs(a);
d = fabs(b);
c > d ? c : d;

This line doesn't do anything. Did you meant to write here

d = d ? c : d;

return d == 0.0 ? 0.0 : fabs(a - b) / d;
}

I broke it down into two functions because I thought it might be
useful to calculate the relative difference separately. And yes,
I know that C99 introduced a boolean type.

What about something like this:

int dbl_is_nearly_equal( double a, double b )
{
double max_of_both = fsbs( a ) > fabs( b ) ? a : b;
if ( max_of_both == 0.0 )
return 1;
return fabs( ( a - b ) / max_of_both ) < DBL_EPSILON;
}

Of course you can pick a larger relative difference than
DBL_EPSILON (but a smaller won't make much sense).

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@xxxxxxxxxxx
\__________________________ http://toerring.de
.



Relevant Pages

  • Re: comparing doubles for equality
    ... Jens Thoms Toerring wrote: ... I came up with this solution based on the notion of relative difference. ... and probably not an uncommon number in scientific calculations. ... some countries;-) won't fit into an int ...
    (comp.programming)
  • Re: comparing doubles for equality
    ... equality, I came up with this solution based on the notion of ... relative difference. ... This probably will fail for numbers that can't be represented as ... some countries;-) won't fit into an int ...
    (comp.programming)
  • Re: comparing doubles for equality
    ... relative difference. ... Correction, ... int double_compare ... int float_compare ...
    (comp.programming)