doumor942473 2017-09-22 23:05
浏览 550
已采纳

在Go运算中处理浮点数精度?

I'm interested in a way to accurately subtract 2 float's in Go.

I've tried to use the math/big library but I can't get an accurate result.

I've used the big.js library in Javascript which solves this problem. Is there a similar library/method for Go arithmetic?

    package main

    import (
        "fmt"
        "math/big"
    )

    func main() {
        const prec = 200
        a := new(big.Float).SetPrec(prec).SetFloat64(5000.0)
        b := new(big.Float).SetPrec(prec).SetFloat64(4000.30)
        result := new(big.Float).Sub(a, b)
        fmt.Println(result)
    }
    Result: 999.6999999999998181010596454143524169921875

https://play.golang.org/p/vomAr87Xln

  • 写回答

2条回答 默认 最新

  • doushoubu5360 2017-09-22 23:08
    关注

    Package big

    import "math/big"

    func (*Float) String

    func (x *Float) String() string
    

    String formats x like x.Text('g', 10). (String must be called explicitly, Float.Format does not support %s verb.)

    Use string input and round the output, for example,

    package main
    
    import (
        "fmt"
        "math/big"
    )
    
    func main() {
        const prec = 200
        a, _ := new(big.Float).SetPrec(prec).SetString("5000")
        b, _ := new(big.Float).SetPrec(prec).SetString("4000.30")
        result := new(big.Float).Sub(a, b)
        fmt.Println(result)
        fmt.Println(result.String())
    }
    

    Output:

    999.6999999999999999999999999999999999999999999999999999999995
    999.7
    

    For decimal, by definition, binary floating-point numbers are an approximation. For example, the decimal number 0.1 cannot be represented exactly, it is approximately 1.10011001100110011001101 * (2**(-4)).

    You are already used to this sort of thing since you know about repeating decimals, an approximation for rational numbers: 1 / 3 = .333... and 3227 / 555 = 5.8144144144....

    See What Every Computer Scientist Should Know About Floating-Point Arithmetic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题
  • ¥15 找会编程的帅哥美女 可以用MATLAB里面的simulink编程,用Keil5编也可以。
  • ¥15 已知隐函数其中一个变量τ的具体值,求另一个变量
  • ¥15 r语言Hurst指数
  • ¥15 RT-Thread Studio编译问题