0

Check this code:

float velocity, acc, time;
.
.
velocity = velocity - acc * time

if( velocity == 0.0 )
{
   // Do something
}
else
{
   // Do something else
}

This code isn't always workng. When the velocity is supposed to be exact 0, it sometimes turns out to be something really small, like 2e-09 or something, but not absolute zero.
How do I make this work?

2
Contributors
2
Replies
3
Views
10 Years
Discussion Span
Last Post by vicky_dev
0

http://en.wikipedia.org/wiki/Floating_point
Never compare floats using == or !=
Your answer may be very close to zero, but if it's even the tiniest bit off, then your code will fail.

Floating point numbers are approximations, which means you need to make approximate comparisons, or range comparisons.

So rather than == 0, do something like if ( velocity >= 0 ) or if ( fabs(velocity) < 0.001 ) Here's another example of someone coming unstuck with the approximate nature of floats.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.