go - 将 float 打印为字符串时的精度损失

标签 go floating-point

<分区>

如果我将 int 数字存储到一个结构中,然后对它们应用除法,我就碰巧遇到了这种情况。精度会丢失。

func main() {
   var x = 94911151
   var y = 94911150
   // If we use the value to calculate division directly, it would be fine
   var result1 = float64(94911151)/94911150
   var result2 = float64(x)/float64(y)
   fmt.Println(result1, result2)
   // If we pass the values directly as parameter into a function and then apply division, it would be fine
   getParas(x,y)
   // If we pass the values into a stuct, and then retrieve the value from struct, then apply division, the precision would be lost.
   getLinearParas(Point{x,y},Point{0,0})
}

func getParas(a int, b int){
    diffX := a -0
    diffY := b-0
    c:= float64(diffX) / float64(diffY)
    fmt.Println(c)
}

type Point struct{
    X int
    Y int
}

func getLinearParas(point1 Point, point2 Point)  {
    diffX := point1.X - point2.X
    diffY := point1.Y - point2.Y
    a := float64(diffX) / float64(diffY)
    fmt.Printf("diffY: %d; diffX:%d ; a:%f \n", diffY, diffX, a)
}

就像代码一样,如果我将 int 值放入一个结构中,然后对它们应用除法。精度会以某种方式丢失。 以上代码运行结果为

 1.00000001053617 1.00000001053617
 1.00000001053617
 diffY: 94911150; diffX:94911151 ; a:1.000000 

或者你可以自己去 Playground 试试 https://play.golang.org/p/IDS18rfv9e6

谁能解释为什么会这样?以及如何避免这种损失? 非常感谢。

最佳答案

将格式字符串中的%f更改为%v%g%.14ffmt.Println 打印等同于 %v 的内容,对于 float64,%v 被视为 %g%f 默认打印 6 位有效数字的值,%g 使用“唯一标识值所需的最小数字位数”。

关于go - 将 float 打印为字符串时的精度损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48201078/

相关文章:

debugging - 如何分析这个 Golang cpu pprof 快照?

go - 我如何在 Go 上模拟一个方法?

c - float 到 double (IEEE754) 转换

math - float 学有问题吗?

hash - Go:这个散列函数的范围如何从 0-32 位?

go - 如何将 HTTP 响应写入标准输出?

go - 对多级返回的 panic

c++ - 当一个相对较大的浮点值与两个相对较小的浮点值相乘时,消除误差的最佳算术顺序是什么

java - 在 Java (Eclipse) 中默认使用 float

math - float 学有问题吗?