问题描述
在Go中丢失了将float32数字转换为float64精度的过程.例如,将359.9转换为float64会生成359.8999938964844.如果float32可以精确存储,为什么float64会丢失精度?
While converting a float32 number to float64 precision is being lost in Go. For example converting 359.9 to float64 produces 359.8999938964844. If float32 can be stored precisely why is float64 losing precision?
示例代码:
package main
import (
"fmt"
)
func main() {
var a float32 = 359.9
fmt.Println(a)
fmt.Println(float64(a))
}
在
推荐答案
从 float
(即float32)转换为 double时,您从不失去精度
(float64).前者必须是后者的子集.
You never lose precision when converting from a float
(i.e. float32) to a double
(float64). The former must be a subset of the latter.
更多与输出格式化程序的默认精度有关.
It's more to do with the defaulting precision of the output formatter.
最接近359.9的IEEE754 float
是
The nearest IEEE754 float
to 359.9 is
359.899993896484375
最接近359.9的IEEE754 double
是
The nearest IEEE754 double
to 359.9 is
359.8999999999999772626324556767940521240234375
距离359.899993896484375最近的IEEE754 double
是
The nearest IEEE754 double
to 359.899993896484375 is
359.899993896484375
(即是相同的;由于我已经提到过子集规则).
(i.e. is the same; due to the subsetting rule I've already mentioned).
因此您可以看到 float64(a)
与 float64(359.899993896484375)
相同,即 359.899993896484375
.这说明了该输出,尽管格式化程序将最后两位数字四舍五入.
So you can see that float64(a)
is the same as float64(359.899993896484375)
which is 359.899993896484375
. This explains that output, although your formatter is rounding off the final 2 digits.
这篇关于为什么在将float32转换为float64时会失去精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!