0

我遇到了一些有趣的 Golang big.Float 计算问题。

问题是

10001000100010001000100010001000100010001000100015.5533 / 1000000000000000000

= 10001000100010001000100010001000.1000100010001000155533

However, big.Float gave "10001000100010001000100010001000.10001000100010001555329999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997"

编码:

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\n", prec)
fmt.Printf("Quotient: %s\n", q.Text('f', -1))

结果:

Percision: 1024
Quotient: 10001000100010001000100010001000.10001000100010001555329999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997

更令人困惑的是,如果我设置 prec = 512,更小的精度,它会产生正确的结果。

Percision: 512
Quotient: 10001000100010001000100010001000.1000100010001000155533

有人知道我的代码有什么问题或如何配置 big.Float 以获得预期结果吗?

谢谢大家!

4

1 回答 1

4

来自go doc math/big.Float

非零有限浮点数表示多精度浮点数

符号 × 尾数 × 2**指数

0.5 <= 尾数 < 1.0,MinExp <= 指数 <= MaxExp。

并且 SetPrec 设置尾数的位宽而不是一些十进制精度。

与 float64s 一样,并非每个十进制数都可以在 big.Float 中精确表示,您的代码显示了这一点。您看到 prec=512 所期望看到的事实是由于不同的舍入和打印。

经验法则:big.Floats 表现得像“正常”浮点数,但有所有缺点(这里不是每个小数都可以表示),但可能显示出较少的舍入错误。

于 2019-05-14T15:49:12.037 回答