Re: comparing doubles for equality
- From: Logan Shaw <lshaw-usenet@xxxxxxxxxxxxx>
- Date: Sun, 29 Apr 2007 15:37:18 -0500
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.
- Logan
.
- Follow-Ups:
- Re: comparing doubles for equality
- From: Bjørn Augestad
- Re: comparing doubles for equality
- 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
- 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
|