Saturday, March 30, 2019

c++ - comparing float variable

When comparing floats, you have to compare them for being "close" instead of "equal." There are multiple ways to define "close" based on what you need. However, a typical approach could be something like:


namespace FloatCmp {
const float Eps = 1e-6f;
bool eq(float a, float b, float eps = Eps) {
return fabs(a - b) < eps;
}
//etc. for neq, lt, gt, ...
}

Then, use FloatCmp::eq() instead of == to compare floats.

No comments:

Post a Comment