dourong4031 2018-01-11 06:34
浏览 44
已采纳

打印成串浮起时的精度损失[关闭]

It just happened to me that if I store int number into a struct and later apply division with them. The precision would be lost.

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 
", diffY, diffX, a)
}

Like the code, If I put int values into a struct, and later apply division on them. the precision would be lost somehow. The result of running above code is

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

Or you can try it yourself in playground https://play.golang.org/p/IDS18rfv9e6

Could anyone explain why this happens? and how to avoid such loss? Thank you very much.

  • 写回答

1条回答 默认 最新

  • dongxian1699 2018-01-11 07:34
    关注

    Change %f in the format string to %v or %g or %.14f. fmt.Println prints things with the equivalent of %v, %v for float64 is treated as %g. %f prints values with 6 significant digits by default, %g uses "the smallest number of digits necessary to identify the value uniquely".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分