Re: comparing doubles for equality
- From: Bjørn Augestad <boa@xxxxxxxxxxxxxx>
- Date: Mon, 30 Apr 2007 06:58:41 +0200
Logan Shaw wrote:
Bjørn Augestad wrote:Here's how I do it (more or less):
#define TOLERANCE 0.0000001
int dbl_isequal(double a, double b)
{
return (fabs(a - b) < TOLERANCE) ? 1 : 0;
}
Works for me.
That works if your numbers stay within a certain range (which may indeed
be the case in some programs), but it eventually fails once you start to
get relatively big numbers. Here's a program:
#include <stdio.h>
#include <math.h>
#define TOLERANCE 0.0000001
int dbl_isequal(double a, double b)
{
return (fabs(a - b) < TOLERANCE) ? 1 : 0;
}
int main()
{
double u = 1.0;
double v = u + 1e-14;
double big = 1.0;
big *= 1<<16;
big *= 1<<16;
big *= 1<<16;
big *= 1<<16;
printf ("%g == %g? %s.\n", u, v, dbl_isequal(u, v) ? "yes" : "no");
u *= big;
v *= big;
printf ("%g == %g? %s.\n", u, v, dbl_isequal(u, v) ? "yes" : "no");
return 0;
}
And here's its output:
1 == 1? yes.
1.84467e+19 == 1.84467e+19? no.
It seems odd that multiplying two "equal" numbers by the same value,
especially when that value is a power of two and can be represented
exactly as a 64-bit IEEE-754 floating point number, causes them to
afterwards be unequal.
Thanks for an interesting example. I guess one can say that your code snippet express tolerance as a percentage of the two numbers and my snippet use an absolute max tolerance. Because of that, my code does not scale when the numbers get really big. OTOH, your version accepts huge absolute differences because the numbers compared are astronomical.
Bjørn
.
- References:
- comparing doubles for equality
- From: Richard Weeks
- Re: comparing doubles for equality
- From: Logan Shaw
- Re: comparing doubles for equality
- From: Bjørn Augestad
- Re: comparing doubles for equality
- From: Logan Shaw
- comparing doubles for equality
- Prev by Date: Re: comparing doubles for equality
- 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
|