dplece1882 2019-05-14 15:03
浏览 1709
已采纳

Golang big.Float的精度问题

I've met some interesting problem of Golang big.Float calculation.

The Problem is

10001000100010001000100010001000100010001000100015.5533 / 1000000000000000000

= 10001000100010001000100010001000.1000100010001000155533

However, big.Float gave "10001000100010001000100010001000.10001000100010001555329999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997"

The code:

var prec uint = 1024 // 512
dec, _ := new(big.Float).SetPrec(prec).SetString("1000000000000000000")
f, _ := new(big.Float).SetPrec(prec).SetString("10001000100010001000100010001000100010001000100015.5533")
q := f.Quo(f, dec)

fmt.Printf("Percision: %d
", prec)
fmt.Printf("Quotient: %s
", q.Text('f', -1))

Result:

Percision: 1024
Quotient: 10001000100010001000100010001000.10001000100010001555329999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997

And the more confusing part is, if I set prec = 512, a smaller precision, it produced correct result instead.

Percision: 512
Quotient: 10001000100010001000100010001000.1000100010001000155533

Doses any one know what's wrong of my code or how to configure big.Float to get expected result?

Thanks to all!

  • 写回答

1条回答 默认 最新

  • dragon4587 2019-05-14 15:49
    关注

    From go doc math/big.Float:

    A nonzero finite Float represents a multi-precision floating point number

    sign × mantissa × 2**exponent

    with 0.5 <= mantissa < 1.0, and MinExp <= exponent <= MaxExp.

    And SetPrec sets the bitwidth of the mantissa not some decimal precision.

    Like with float64s not every decimal number can be represented exact in a big.Float and your code shows this. The fact that you see what you expect to see with prec=512 is due to different rounding and printing.

    Rule of thumb: big.Floats behave like "normal" floats with all their shortcomings (here not every decimal fraction can be represented) but may show less rounding errors.

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

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波