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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c