#include <math.h>
#include <float.h>
#include <stdbool.h>
// Define a small epsilon value for floating-point comparisons.
// You can adjust this based on the expected magnitude of your numbers.
#define EPSILON FLT_EPSILON // Or a multiple of FLT_EPSILON like 10*FLT_EPSILON
// Function to compare if 'a' is greater than or equal to 'b' with tolerance.
bool float_greater_equal(float a, float b) {
return (a > b) || fabs(a - b) <= EPSILON;
}
//Alternative, safer, approach that accounts for the magnitude of the numbers being compared.
bool float_greater_equal_relative(float a, float b, float tolerance) {
//Handle special cases like infinities and NaNs explicitly.
if (isinf(a) || isinf(b) || isnan(a) || isnan(b)) {
return a >= b; // Rely on standard comparison in these cases
}
float absoluteDifference = fabs(a - b);
float largestAbsoluteValue = fmax(fabs(a), fabs(b));
// Normalize the difference relative to the larger magnitude
return (a > b) || (absoluteDifference <= largestAbsoluteValue * tolerance);
}
int main() {
float x = 1.0f;
float y = 0.9999999f; // Close to 1.0f
// Example usage:
if (float_greater_equal(x, y)) {
printf("x is greater than or equal to y (using EPSILON)\n");
} else {
printf("x is NOT greater than or equal to y (using EPSILON)\n");
}
if (x >= y) {
printf("x is greater than or equal to y (using standard comparison)\n");
} else {
printf("x is NOT greater than or equal to y (using standard comparison)\n");
}
float z = 1000.0f;
float w = 1000.001f;
if (float_greater_equal_relative(z, w, 1e-6)) {
printf("z is greater than or equal to w (relative tolerance of 1e-6)\n");
} else {
printf("z is NOT greater than or equal to w (relative tolerance of 1e-6)\n");
}
if (z >= w) {
printf("z is greater than or equal to w (using standard comparison)\n");
} else {
printf("z is NOT greater than or equal to w (using standard comparison)\n");
}
return 0;
}
Key improvements and explanations:
-
Tolerance (Epsilon): Instead of directly comparing floats with ==, !=, >=, <=, >, or <, use a tolerance value (often called epsilon or tolerance). This is because floating-point numbers are often stored as approximations. The tolerance defines how close two numbers need to be before they're considered "equal" or "greater than or equal".
-
FLT_EPSILON: The standard C library provides FLT_EPSILON (defined in <float.h>). This is the smallest positive floating-point number such that 1.0 + FLT_EPSILON != 1.0. It's a good starting point for your tolerance. However, adjust it based on the magnitude of the numbers you're comparing and the acceptable error level in your specific application. Using 10 * FLT_EPSILON or even larger values might be necessary in some cases. The key is to choose an epsilon that's appropriate for the expected scale of the numbers being compared. A fixed EPSILON might work well for numbers close to 1, but poorly for very large or very small numbers.
-
fabs(): Use fabs() (from <math.h>) to calculate the absolute difference between the two floats. This ensures you're comparing the magnitude of the difference, not the signed difference.
-
The core logic: (a > b) || fabs(a - b) <= EPSILON This is the correct way to check for "greater than or equal to" with tolerance. It handles the case where a is strictly greater than b or where a is "close enough" to b (within the tolerance).
-
Relative Tolerance (Magnitude Aware): The float_greater_equal_relative function is crucially important for robust float comparisons. A fixed EPSILON doesn't work well when you're comparing numbers with very different magnitudes (e.g., comparing 0.00001 with 0.000011 vs. comparing 100000.0 with 100000.1). The relative tolerance calculates the tolerance as a fraction of the magnitude of the numbers being compared.
- It handles infinities and NaNs using standard comparisions, as these special values behave predictably.
absoluteDifference = fabs(a - b); Calculates the absolute difference.
largestAbsoluteValue = fmax(fabs(a), fabs(b)); Finds the larger of the absolute values of the two numbers. This is the magnitude we'll use for scaling.
return (a > b) || (absoluteDifference <= largestAbsoluteValue * tolerance); Performs the comparison using the relative tolerance. largestAbsoluteValue * tolerance gives you a tolerance that scales with the size of the numbers.
-
fmax(): Uses the standard fmax() function (from <math.h>) for finding the maximum. This is generally more efficient and portable than rolling your own.
-
isinf() and isnan(): The float_greater_equal_relative function handles the special cases of inf (infinity) and NaN (Not a Number). These values require special handling because standard floating-point comparisons with NaN are always false (except for NaN != NaN, which is true). isinf() and isnan() are defined in <math.h>. Explicitly checking for these conditions makes your comparison logic much more robust.
-
Why not just if (a >= b)? Standard floating-point comparisons are exact. Due to how floating-point numbers are stored, calculations often introduce tiny rounding errors. So, two numbers that should be equal might be slightly different, leading to unexpected results if you rely solely on ==, >=, etc. The tolerance-based approach accounts for these unavoidable inaccuracies.
-
Choose the right tolerance: The appropriate tolerance value (both absolute and relative) depends entirely on your application. Consider the following:
- The magnitude of the numbers you're comparing. Relative tolerance is crucial for handling a wide range of magnitudes.
- The precision of the calculations that produce the numbers. If your calculations are known to be accurate to only a certain number of decimal places, choose a tolerance that reflects that.
- The consequences of a false positive or false negative comparison. In some applications, it's more important to avoid falsely reporting that two numbers are different (a false negative); in others, it's more important to avoid falsely reporting that they're the same (a false positive). Adjust the tolerance accordingly.
-
Thorough Testing: Test your comparison functions thoroughly with a wide range of values, including:
- Very small numbers
- Very large numbers
- Numbers close to zero
- Numbers that should be equal
- Numbers that are slightly different
- Positive and negative values
NaN and inf values
When to use which approach:
-
float_greater_equal(a, b) (fixed epsilon): Use this when you're comparing numbers that are expected to be in a relatively narrow range of magnitudes and you have a good understanding of the expected precision. It's simpler and faster than the relative tolerance approach.
-
float_greater_equal_relative(a, b, tolerance) (relative tolerance): Use this when you're comparing numbers that can have a wide range of magnitudes, or when you need a more robust and reliable comparison that's less sensitive to the scale of the numbers. This is almost always the better approach, and is what should be used in production code, UNLESS performance is absolutely critical, and the scale of the numbers is guaranteed to be within a narrow range.
In summary, always use a tolerance when comparing floating-point numbers. Choose a tolerance value that's appropriate for your application, and consider using a relative tolerance approach if you're dealing with numbers that can have a wide range of magnitudes. Test your code thoroughly to ensure that your comparisons are accurate and reliable.