duanjia1870 2017-03-16 06:32 采纳率: 0%
浏览 806

这是strconv.ParseFloat()行为的预期还是错误? 我该如何解决?

Run this code to see what I mean: Go Playground demo of issue

package main

import (
    "fmt"
    "strconv"
)

func main() {
    // From https://golang.org/src/math/const.go
    var SmallestNonzeroFloat64AsString string = "4.940656458412465441765687928682213723651e-324"
    var SmallestNonzeroFloat64 float64
    var err error
    SmallestNonzeroFloat64, err = strconv.ParseFloat(SmallestNonzeroFloat64AsString, 64)
    if err != nil {
        panic(err)
    }
    fmt.Printf("SmallestNonzeroFloat64 = %g
", SmallestNonzeroFloat64)
    fmt.Printf("SmallestNonzeroFloat64 = %s
", strconv.FormatFloat(SmallestNonzeroFloat64, 'f', -1, 64))
}

SmallestNonzeroFloat64 is defined in math/const.go and I assumed it can be represented by a float64 variable.

But when it is parsed into a float64 with strconv.ParseFloat() and printed with strconv.FormatFloat() the result is rounded.

Instead of 4.940656458412465441765687928682213723651e-324 I get 5e-324 (or its non-exponent equivalent, which you can see in the Go Playground results). The result is rounded.

Is there a way to get back the 4.940656458412465441765687928682213723651e-324?

Or is it a bug?

  • 写回答

1条回答 默认 最新

  • doushi5913 2017-03-16 06:47
    关注

    This is not a bug.

    You could ask Go to print more digits.

    fmt.Printf("SmallestNonzeroFloat64 = %.40g
    ", SmallestNonzeroFloat64)
    // 4.940656458412465441765687928682213723651e-324
    

    However, 5e-324 and 4.94…e-324 are in fact the same value, so Go is not wrong printing 5e-324. This value (2-1074) is the smallest positive number representable by Float64 (also known as double in other languages). Larger numbers are all multiples of this, e.g. the next smallest number would be 2 × 2-1074 = 1e-323, the next would be 3 × 10-1074 = 1.5e-323, etc.

    In the other words, all numbers more precise than 5e-324 would not be representable in Float64. So it makes no sense to print more digit after the "5". And 5e-324 is certainly more readable than 4.94…e-324.

    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计