【问题标题】:golang How to get the correct result? floating point arithmetic issuesgolang 如何得到正确的结果?浮点运算问题
【发布时间】:2022-01-19 03:24:39
【问题描述】:
testA, testB, testC := big.NewFloat(0), big.NewFloat(0), big.NewFloat(0)
testA.SetPrec(500)
testB.SetPrec(500)
testA.SetString("0.081531021188798896")
testB.SetString("0.9975")
testC.Mul(testA, testB)
testD := testC.Text('f', 500)
fmt.Println("testC", testD)

go结果是

0.081327193635826897089025...

而实际结果是

0.08132719363582689876

https://www.calculator.net/big-number-calculator.html生成

go结果很接近,但不正确

【问题讨论】:

  • 您正在使用 floats 进行计算。如果您想要准确的结果,请使用有理数 (big.Rat) 进行计算。通过将精度提高到过高的值,浮点数的计算不会神奇地变得“正确”。您的问题是,不可能将 0.9975 精确地呈现为浮点数。见0.30000000000000004.com
  • 你也打算testC.SetPrec(500)吗?

标签: go floating-point precision floating-accuracy


【解决方案1】:
testA, _ := new(big.Rat).SetString("0.081531021188798896")
testB, _ := new(big.Rat).SetString("0.9975")
// testB = new(big.Rat).SetFloat64(0.9975) error
testC := new(big.Rat).Mul(testA, testB)
fmt.Println("testC", testC)
testD := testC.FloatString(500)
fmt.Println("testD", testD)
fmt.Println("trueD", "0.08132719363582689876")

https://go.dev/play/p/1c7R2neS2sD

【讨论】:

    猜你喜欢
    • 2019-08-26
    • 2018-10-25
    • 2012-08-10
    • 1970-01-01
    • 2016-05-02
    • 2023-03-15
    • 2018-08-17
    • 2020-11-09
    • 1970-01-01
    相关资源
    最近更新 更多