Difference in Float64 Precision: Unpacking Varying Values
Consider the following example in Go:
fmt.Println(912 * 0.01) fmt.Println(float64(912) * 0.01)
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!