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.

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

报告相同问题?

悬赏问题

  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答