Home >Backend Development >C++ >When is it Safe to Use the Equality Operator for Floating-Point Comparisons?
When is Floating-Point Comparison Acceptable?
In programming, comparing floating-point numbers with the equality operator (= =) is generally discouraged due to inherent inaccuracies in their representation. However, there are limited scenarios where such comparisons can be considered reliable.
Exact Representations of Integers
IEEE 754, the widely adopted standard for floating-point arithmetic, guarantees that float representations of integers within a specific range are exact. Therefore, whole numbers, including zero, can be compared using the equality operator.
Example:
float a = 1.0; float b = 1.0; a == b; // True
Integral Constants
Using constants defined as static const double, like the BAR constant in the example code, ensures that the value is represented as an exact floating-point number. Thus, comparing a variable with such a constant using the equality operator will always produce the correct result.
Example:
static const double BAR = 3.14; void foo(double d) { if (d == BAR) ... }
In this case, foo(BAR) will always evaluate to true, assuming no other calculations or operations modify the d variable.
Cautionary Notes
While floating-point comparisons of integers are generally reliable, caution is still advised.
The above is the detailed content of When is it Safe to Use the Equality Operator for Floating-Point Comparisons?. For more information, please follow other related articles on the PHP Chinese website!