When comparing two floating-point numbers in C, you should avoid direct comparisons using ==, >=, <=, etc., due to precision issues. Instead, you should use a small epsilon value to account for floating-point rounding errors.
Best Practices for Comparing Floats in C:
-
Use an Epsilon Value:
Define a small epsilon value (e.g., 1e-9 or 1e-6) to check if two floats are "close enough."
-
Avoid Direct Comparisons:
Never use ==, >=, or <= directly on floating-point numbers.
-
Use fabs() for Absolute Difference:
Compare the absolute difference between the two numbers against epsilon.
Example Code:
#include <stdio.h>
#include <math.h> // For fabs()
#define EPSILON 1e-9
int areFloatsEqual(float a, float b) {
return fabs(a - b) < EPSILON;
}
int isGreaterOrEqual(float a, float b) {
return (a - b) > -EPSILON; // a >= b within epsilon
}
int main() {
float x = 0.1f + 0.2f;
float y = 0.3f;
if (areFloatsEqual(x, y)) {
printf("x and y are approximately equal.\n");
} else {
printf("x and y are NOT equal.\n");
}
if (isGreaterOrEqual(x, y)) {
printf("x is greater than or equal to y.\n");
} else {
printf("x is less than y.\n");
}
return 0;
}
Explanation:
areFloatsEqual(a, b) checks if a and b are approximately equal by comparing their difference to EPSILON.
isGreaterOrEqual(a, b) checks if a is greater than or equal to b within EPSILON tolerance.
fabs() computes the absolute value of the difference.
Choosing an Epsilon:
- The value of
EPSILON depends on the expected precision of your application.
- Common choices are
1e-6 (for general use) or 1e-9 (for higher precision).
Alternative (Using nextafter for More Robust Checks):
For more precise comparisons, you can use nextafter to check if a is greater than or equal to b within a small margin:
#include <math.h>
int isGreaterOrEqual(float a, float b) {
return a > b - EPSILON;
}
Conclusion:
Always use an epsilon-based comparison for floating-point numbers in C to avoid precision-related bugs. Direct comparisons (==, >=, <=) should be avoided.