Home > Backend Development > Golang > How Can I Efficiently Compare Floating-Point Numbers for Near Equality in Go?

How Can I Efficiently Compare Floating-Point Numbers for Near Equality in Go?

Linda Hamilton
Release: 2024-12-07 14:07:15
Original
787 people have browsed it

How Can I Efficiently Compare Floating-Point Numbers for Near Equality in Go?

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
}
Copy after login

Evaluation:

While this approach may seem promising, it suffers from limitations:

  • Loss of Precision: Bitwise comparison ignores the precision of the floats, leading to potential inaccuracies.
  • Inconsistent Results: Depending on the specific binary representation, this method may not always return consistent results. For example, two floats with the same magnitude but different signs may have identical bitwise representations.

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template