Middle
How would you compare two floating-point numbers for equality?
sobes.tech AI
Answer from AI
Comparing floating-point numbers for strict equality (==) is not recommended due to their internal representation and possible rounding errors. Instead, a comparison with a tolerance (epsilon) is used:
#include <cmath> // For std::fabs
bool are_equal_float(float a, float b, float epsilon = 0.00001f) {
// Compare the absolute difference of the numbers with the given tolerance
return std::fabs(a - b) < epsilon;
}
// Example usage:
// float x = 0.1f + 0.2f;
// float y = 0.3f;
// if (are_equal_float(x, y)) {
// // The numbers are considered equal
// }
The choice of the epsilon value depends on the specific accuracy requirements.