Re: comparing doubles for equality
- From: Richard Weeks <rweeks@xxxxxxxxxx>
- Date: Mon, 30 Apr 2007 13:40:08 GMT
nag wrote:
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.
Sorry about that. It should be part of the return statement:
return d==0.0 ? 0.0 : fabs(a-b) / (c>d ? c : d);
i.e. divide the absolute difference of a,b by whichever has the largest absolute value.
.
- References:
- comparing doubles for equality
- From: Richard Weeks
- Re: comparing doubles for equality
- From: nag
- comparing doubles for equality
- Prev by Date: iTechArt Group - Custom Software Development and Offshore outsourcing Company
- Next by Date: Re: comparing doubles for equality
- Previous by thread: Re: comparing doubles for equality
- Next by thread: Re: comparing doubles for equality
- Index(es):
Relevant Pages
|