Home > Backend Development > Golang > Why Does `912 * 0.01` Differ from `float64(912) * 0.01` in Go?

Why Does `912 * 0.01` Differ from `float64(912) * 0.01` in Go?

Linda Hamilton
Release: 2024-12-16 19:00:15
Original
571 people have browsed it

Why Does `912 * 0.01` Differ from `float64(912) * 0.01` in Go?

Difference in Float64 Precision: Unpacking Varying Values

Consider the following example in Go:

fmt.Println(912 * 0.01)
fmt.Println(float64(912) * 0.01)
Copy after login

The first statement prints 9.12, while the second yields 9.120000000000001. This apparent difference in precision can be puzzling.

According to the Go Language Specification, constant expressions are evaluated exactly. In this case, 912 * 0.01 is a constant expression. Evaluating it exactly produces 9.12, which is subsequently assigned to float64(912 * 0.01) and passed to fmt.Println().

Alternatively, float64(912) * 0.01 is also a constant expression. However, the left operand, originally an integer, is explicitly cast to float64 before multiplication. This means that 0.01 is implicitly converted to float64 as well, resulting in multiplication between two float64 values.

Crucially, 0.01 is not precisely representable as a float64. It is rounded to the nearest representable value, which introduces slight imprecision. As a result, float64(912) * 0.01 evaluates to 9.120000000000001, which is then printed.

In summary, the difference in output arises from the evaluation of constant expressions: whether the cast occurs before or during the evaluation, and whether imprecision is introduced due to the limitation of float64 precision.

The above is the detailed content of Why Does `912 * 0.01` Differ from `float64(912) * 0.01` 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