Home >Backend Development >Golang >Why Does Floating-Point Equality Fail in Go When Comparing Variables and Literals?

Why Does Floating-Point Equality Fail in Go When Comparing Variables and Literals?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-24 05:34:20613browse

Why Does Floating-Point Equality Fail in Go When Comparing Variables and Literals?

Floating-Point Precision in Go: Understanding the Difference Between Literals and Variables

The Discrepancy

In Go, the following code snippet reveals an intriguing difference in floating-point calculations:

package main

import (
    "fmt"
)

func main() {
    x := 10.1
    fmt.Println("x == 10.1:        ", x == 10.1)
    fmt.Println("x*3.0 == 10.1*3.0:", x*3.0 == 10.1*3.0)
}

When executed, this code produces unexpected results:

x == 10.1:         true
x*3.0 == 10.1*3.0: false

While the same floating-point operations are performed, using either a declared variable (x) or a literal (10.1), the equality check fails.

Origin of the Difference

To understand this behavior, one must delve into Go's handling of floating-point numbers. Constants and number literals are initially untyped and possess无限精度. However, when assigned to a variable or type-converted, they inherit the limitations of the destination type.

When x := 10.1 is assigned, the literal 10.1 loses some precision due to conversion to a float. Conversely, 10.1*3.0 maintains its full precision in the calculation. This accounts for the observed difference in values and the false equality check.

Documentation and Rationale

This behavior is outlined in the "Floats" section of Go's blog post on constants:

"Numeric constants live in an arbitrary-precision numeric space; they are just regular numbers. But when they are assigned to a variable the value must be able to fit in the destination."

While the mechanisms behind this behavior, particularly in cases with extremely large constants, remain somewhat obscure, it provides a valuable insight into the intricacies of floating-point representation in Go. This knowledge allows developers to anticipate and handle precision-related issues in their code effectively.

The above is the detailed content of Why Does Floating-Point Equality Fail in Go When Comparing Variables and Literals?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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