Re: comparing doubles for equality
- From: Richard Weeks <rweeks@xxxxxxxxxx>
- Date: Mon, 30 Apr 2007 17:31:46 GMT
Jens Thoms Toerring wrote:
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)
In which case standard C (without extended precision routines) will be inadequate for the calculations anyway.
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).
I guess I will go with this Jens, and resign myself to the lack of a general solution to this problem.
Richard
.
- Follow-Ups:
- Re: comparing doubles for equality
- From: Jens Thoms Toerring
- Re: comparing doubles for equality
- References:
- comparing doubles for equality
- From: Richard Weeks
- Re: comparing doubles for equality
- From: Jens Thoms Toerring
- comparing doubles for equality
- Prev by Date: OT somewhat: Do you telecommute? What do you wish the boss understood about it?
- Next by Date: Re: OT somewhat: Do you telecommute? What do you wish the boss understood about it?
- Previous by thread: Re: comparing doubles for equality
- Next by thread: Re: comparing doubles for equality
- Index(es):
Relevant Pages
|