Go Float Comparison: An Efficient Approach for Almost Equality
In Go, comparing two floats (float64) for equality can be a tricky task due to the limitations of IEEE 754 floating-point representation. While the conventional "abs(diff) < epsilon" method provides an approximation, it can lead to inconsistencies.
Proposed Solution: Bit-Level Comparison
A proposed solution suggests comparing the bitwise representation of the float64 values. The rationale is that a one-bit difference in binary representation ensures near equality, as any larger difference would result in a different sign bit or exponent.
Implementation:
func Equal(a, b float64) bool { ba := math.Float64bits(a) bb := math.Float64bits(b) diff := ba - bb if diff < 0 { diff = -diff } // accept one bit difference return diff < 2 }
Evaluation:
While this approach may seem promising, it suffers from limitations:
Recommended Solution: Floating-Point Subtraction
A more reliable and efficient approach for almost equality is to simply subtract the two floats and check if the difference is smaller than a pre-defined threshold:
const float64EqualityThreshold = 1e-9 func almostEqual(a, b float64) bool { return math.Abs(a - b) <= float64EqualityThreshold }
This method preserves the precision of the floats and provides consistent results, making it a robust solution for comparing float64 values for near equality.
The above is the detailed content of How Can I Efficiently Compare Floating-Point Numbers for Near Equality in Go?. For more information, please follow other related articles on the PHP Chinese website!