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

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.

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

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)