Home > Backend Development > Golang > How Can I Accurately and Efficiently Compare Floating-Point Numbers in Go?

How Can I Accurately and Efficiently Compare Floating-Point Numbers in Go?

DDD
Release: 2024-12-17 21:03:12
Original
578 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template