doushang3352 2017-11-09 23:22
浏览 54
已采纳

为什么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)
}

Produces:

x == 10.1:         true
x*3.0 == 10.1*3.0: false
x*3.0:             30.299999999999997
10.1*3.0:          30.3

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.

  • 写回答

2条回答 默认 最新

  • duanfu7004 2017-11-09 23:37
    关注

    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.

    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)
    

    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.

    How it actually does this, especially in the given Huge case, I do not know.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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