hey guys, what’s the proper way to do floating point compare?
this:
if (rect1.getMinX() == rect2.getMinX() {
// do something
}
or:
if (fabsf(rect1.getMinX() - rect2.getMinX()) == FLT_EPSILON) {
// do something
}
??
hey guys, what’s the proper way to do floating point compare?
this:
if (rect1.getMinX() == rect2.getMinX() {
// do something
}
or:
if (fabsf(rect1.getMinX() - rect2.getMinX()) == FLT_EPSILON) {
// do something
}
??
I’m looking at the framework code itself eg from Node:
void Node::setPosition(float x, float y)
{
if (_position.x == x && _position.y == y)
return;
_position.x = x;
_position.y = y;
_transformUpdated = _transformDirty = _inverseDirty = true;
_usingNormalizedPosition = false;
}
Looks its ok just use comparison operator == instead of FLT_EPSILON
Nooo! spoke too soon!
bool Vec2::equals(const Vec2& target) const
{
return (fabs(this->x - target.x) < FLT_EPSILON)
&& (fabs(this->y - target.y) < FLT_EPSILON);
}
It usually depends since floating-point is weird 
If you set the value directly you can compare against that same value.
float a = 12.345f; // or from method always returns constant/literal
( a == 12.345f ); // true
This is why setPosition compares with == whereas Vec2::equals compares component “distance” (abs difference) with epsilon.
Couple blog posts
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/.
http://realtimecollisiondetection.net/blog/?p=89.
Stackoverflow
https://stackoverflow.com/questions/17333/most-effective-way-for-float-and-double-comparison.