为什么Go中带文字的浮点乘法与变量之间有区别? [英] Why is there a difference between floating-point multiplication with literals vs. variables in Go?
问题描述
为什么以下内容在Go中不相等?这是一个错误,还是设计使然?如果是设计使然,为什么会发生这种现象,并且这种行为在任何地方都有记录?
Why are the following unequal in Go? Is this a bug, or is it by design? If it's by design, why does this occur and is this type of behavior documented anywhere?
https://play.golang.org/p/itEV9zwV2a
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)
fmt.Println("x*3.0: ", x*3.0)
fmt.Println("10.1*3.0: ", 10.1*3.0)
}
产生:
x == 10.1: true
x*3.0 == 10.1*3.0: false
x*3.0: 30.299999999999997
10.1*3.0: 30.3
请注意,正在执行相同的浮点数学运算,只是语法不同.那么结果为何不同?我希望10.1*3.0
等于30.29999...
,如x*3.0
示例中一样.
Note that the same floating point math is being performed, just with different syntax. So why is the result different? I would expect 10.1*3.0
to equal 30.29999...
as in the x*3.0
example.
推荐答案
Go中的常量和数字文字是无类型的,并且具有无限的精度.在必须将其存储为特定类型的那一刻起,将应用该类型的界限.因此,当您声明x := 10.1
时,该文字将转换为float
并失去一些精度.但是,当您专门执行10.1*3.0
时,它们具有其全部精度.
Constants and number literals in Go are untyped and have unlimited precision. The moment it has to be stored as a specific type, the bounds of that type apply. So when you declare x := 10.1
, that literal is converted into a float
and loses some precision. But when you specifically do 10.1*3.0
these have their full precision.
请参阅本文中的浮点数"标题. https://blog.golang.org/constants
See the "Floats" header in this article. https://blog.golang.org/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. We can declare a constant with a very large value:
const Huge = 1e1000
-毕竟这只是一个数字-但是我们无法分配它,甚至无法打印它.该语句甚至不会编译:
—that's just a number, after all—but we can't assign it or even print it. This statement won't even compile:
fmt.Println(Huge)
错误为常数1.00000e + 1000溢出float64",即 真的.但是巨大"也许很有用:我们可以在带有 其他常量,如果结果使用这些表达式的值 可以在float64的范围内表示.
The error is, "constant 1.00000e+1000 overflows float64", which is true. But Huge might be useful: we can use it in expressions with other constants and use the value of those expressions if the result can be represented in the range of a float64.
实际上是如何做到的,尤其是在给定的Huge
情况下,我不知道.
How it actually does this, especially in the given Huge
case, I do not know.
这篇关于为什么Go中带文字的浮点乘法与变量之间有区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!