Re: comparing doubles for equality



On Apr 29, 10:33 pm, Richard Weeks <rwe...@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)
{
fraca = a - (int)a;
fracb = b - (int)b;
reldiff = rel_diff(fraca, fracb);
if(reldiff > MAXRELDIFF) return 0;
else return 1;
}
return 0;

}

double rel_diff(double a, double b)
{
double c, d;
c = fabs(a);
d = fabs(b);
c > 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.

Richard

Hi Richard,

Is something missing in the line commented ending with //****.
I didn't get the usefulness of the expression.

Thanks,
-nag.

.



Relevant Pages

  • Re: comparing doubles for equality
    ... equality, I came up with this solution based on the notion of relative difference. ... /* compare doubles for equality. ... double fraca, fracb, reldiff; ...
    (comp.programming)
  • Re: comparing doubles for equality
    ... /* compare doubles for equality. ... if(reldiff> MAXRELDIFF) return 0; ... useful to calculate the relative difference separately. ...
    (comp.programming)
  • Re: collection framework: using the good interface
    ... The word object's class would implement Comparable, and should have equals and hashCode consistent with compareTo, but I would not make two words equal unless they are, in all respects, the same word. ... I'm more and more convinced that equality should involve all aspects of the Word class, but I'm still uncomfortable with mixing lexicographic information (allowing to compare objects in different collections) and information about frequency, distribution, cooccurrents. ...
    (comp.lang.java.help)
  • Re: If statement
    ... i want to compare atabsin equality ... or call the function atabs passing in the argument i ... since that value is *not* non-zero, ...
    (comp.soft-sys.matlab)
  • Re: [CLOS] Ensuring a method exists
    ... application wants to compare. ... I said "depending on context" for a reason: I think something like dynamically scoped functions or ContextL can be of use here. ... The equality operators in CL are generic in the sense that they are ...
    (comp.lang.lisp)