Advertisement

double==double

Started by August 26, 2000 11:06 AM
2 comments, last by CarlFGauss 24 years, 4 months ago
Assume that I define two variable of type double: double x,y; How accurate is the result if I compare them using the code if (x==y) I am creating a 3D program that use such comparison. I don''t want to catch bug later on so I need to know whether it is safe to use the above code. Thanks for any insights.
As accurate as if you''d used
memcmp(&x,&y,size(double))
(I think that''s the correct syntax)

For equality to work they have to be exactly identical.

You could write a doubleCmp(double x, double y, double err)
that looks at two doubles and sees if they are identical to within a margin of error

BOOL doubleCmp(double x, double y, double err)
{
double diff;

diff = x - y;
diff = fabs(diff);
if(diff < err)
return TRUE;
else
return FALSE;
}

Mike
Advertisement
It might work, but it''d be much safer to use something like:

if( x - y < fabs(range))
DoSomething();

range would just be something like .1. Its best to do it this way since floating point numbers will be unequal with even the smallest variation.

----------------------------------------
"Before criticizing someone, walk a mile in their shoes.
Then, when you do criticize them, you will be a mile away and have their shoes." -- Deep Thoughts

"If you have any trouble sounding condescending, find a Unix user to show you how it's done." - Scott Adams
Doh! Looks like mike beat me to it

----------------------------------------
"Before criticizing someone, walk a mile in their shoes.
Then, when you do criticize them, you will be a mile away and have their shoes." -- Deep Thoughts

"If you have any trouble sounding condescending, find a Unix user to show you how it's done." - Scott Adams

This topic is closed to new replies.

Advertisement