Floating-point Equality: When and Why
While it's generally frowned upon, there are instances where floating-point comparisons can be deemed acceptable.
Exact Representation of Whole Numbers
IEEE 754, the standard for floating-point arithmetic, guarantees that integers (whole numbers) within a certain range are represented exactly in floating-point format. This means that comparisons involving whole numbers, including 0.0, can be made using the equality operator (==).
Cautions with Calculated Values
However, caution is advised when working with floating-point values derived from calculations. Assignment of a whole number to a floating-point variable is safe, but performing any arithmetic operations on floating-point numbers can introduce rounding errors. Hence, equality comparisons between calculated values should be avoided.
Constant Literals
When comparing a variable with a constant literal, it's crucial to ensure that the literal is defined as a double constant (e.g., 3.14L) to maintain double-precision accuracy.
Example
In the provided code snippet, the static const BAR is defined as a double. If d is also a double, then the comparison d == BAR will always return true assuming both d and BAR represent whole numbers within the valid range for floating-point representation.
The above is the detailed content of When Is Floating-Point Equality Acceptable?. For more information, please follow other related articles on the PHP Chinese website!