Link to home
Start Free TrialLog in
Avatar of David MacDonald
David MacDonaldFlag for Canada

asked on

floating point comparison

Haya guys,
       little problem here, i'm trying to compare two floats:

float x, y;

Then let's pretend they receive their values from a bizarre function...

x = bizarreFct();
y = bizarreFct();

if( x > y )  
{
  doACapper();
}

What happens is x and y are both let's says equal to 5.000
But the fct doACapper (purely fictive func by the way -BG-) is still called, the debugger shows that both variable are == 5.

Anyone having a trick to cut the presision of floating point numbers to 3 or 4 decimal...

because x and y are supposed to be == 5 , but our friend the floating point makes them equal to:

x = 5.0000517
y = 5.0000345


Thanks a lot folks!
Avatar of David MacDonald
David MacDonald
Flag of Canada image

ASKER

Btw, i don't want to work with integers, so no need to tell me to cast them, I really have to work with float (damb 3D programming!)
do like this...
#define PRECISION 0.0001
int compare;
compare=(int)((double)(x-y)/(double)PRECISION);


now
negative compare means x<y
positive compare means x>y
0 means both are equal
ASKER CERTIFIED SOLUTION
Avatar of akshayxx
akshayxx
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ssnmoorthy
ssnmoorthy

what akshayxx has written is correct.

Suppose you define

float x=5;
float y=5;

It will be mostly taken as
x=4.999999 in one case and
y=5.000001 in another case. So when you compare like

if(x==y)
{ //this will not be executed
 }

That is (x==y) is evaluated to false or 0.

So it is always good to use

if((fabs(x-y))>0.00001)
{ //do this
 }

or you can define one like

#define eps 0.00001

and use

if((fabs(x-y))>eps)
{ //do this
 }

So you can replace this when ever you compare any float values.
you can try this :

if ( (int)(1000*x) > (int)(1000*y) )
{
 foo();
}

then you get comparison with the desired precision
had he agreed on using int .. there can be so many solutions..
I would suggest you read this if you intend to make extensive use of floating point
http://www.nondot.org/sabre/os/files/Processors/WECSSKAFloatingPoint.pdf
Thanks a lot akshayxx and all of you, thanks Kryp for the docs on floating points.