Home >Backend Development >Golang >How Can I Accurately and Efficiently Compare Floating-Point Numbers in Go?
Go Float Comparison: A More Precise and Efficient Approach
The task of comparing two floating-point numbers (float64) for equality in Go typically involves dealing with the complexities of IEEE 754 and the binary representation of floats. While there are various approaches, some assume that comparing binary representations with a one-bit tolerance is a reliable solution:
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 }
However, this approach has limitations. The binary representation of floating-point numbers isn't always meaningful when comparing their "almost equal" values. A more direct and precise method is to subtract the two numbers to determine their difference:
package main import ( "fmt" "math" ) const float64EqualityThreshold = 1e-9 func almostEqual(a, b float64) bool { return math.Abs(a - b) <= float64EqualityThreshold } func main() { a := 0.1 b := 0.2 fmt.Println(almostEqual(a + b, 0.3)) }
This approach sets a threshold for the maximum acceptable difference and is suitable for most practical scenarios where comparing floats for equality is required. It provides a more precise and efficient solution than comparing binary representations.
The above is the detailed content of How Can I Accurately and Efficiently Compare Floating-Point Numbers in Go?. For more information, please follow other related articles on the PHP Chinese website!