Skip to main content
GameDev.net gamedev.net
🔒 Locked

When does 1==1 return false???

Started by TheSyan Dec 4, 2001 at 4:41 AM 2 replies 400+ views
Original Post
TheSyan
TheSyan
I have a small''ish problem. I have two objects, one stationary with X,Y & Width,Height cords and one moving... I try to check to see it the bottom of the moving object, has touched the top of the non moving one...
  
if ( (Brix.oY-(Brix.Height/2))==((Board[cX][cY].oY)+(Board[cX][cY].Height/2)) )
{
	// Do something....

}
  
Unfortunatly the evaluation, will not return true, even when in debug it clearly shows they are? The 2 values are float type, and as Top = + Bottom = - the signes are right... Why???? and how can this be repaired????
Kippesoep
Kippesoep
If you''re using floats then that''s probably what causes this. Never do an == on floats. Instead of:
  
if (a == b)

do
  
if ((float)fabs (a - b) < 0.001f)

Or use some other small value.
Kippesoep
Oluseyi
Oluseyi
I wouldn''t go as far as saying "never do an == on floats," but it admittedly has hidden complexities. Consider the following code fragment:
float frac = 1.0/1.7, sum = 0.0f;
while(sum != 1.0)
sum += frac;

Being human, you''d expect that the loop body would execute 7 times, right? Well it doesn''t. It executes infinitely because 1.0/7.0 is not an exact value, so sum is never exactly equal to 1.0.

So, as Kippesoep said, use a lt/gt comparison on (absolute) values.
Kippesoep
Kippesoep
Even with perfect precision and fractional loops, your loop would execute only 1.7 times.

You are right of course. It''s not just ==, but also != and the biggest issue is that of constants.
Kippesoep

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.