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?

Recommended Answers

All 2 Replies

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.

Got it, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.