问题描述
我对在Go中精确减去2个浮点数的方法感兴趣.
I'm interested in a way to accurately subtract 2 float's in Go.
我尝试使用math/big
库,但无法获得准确的结果.
I've tried to use the math/big
library but I can't get an accurate result.
我在Javascript中使用了 big.js 库来解决此问题. Go算法有类似的库/方法吗?
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
推荐答案
导入数学/大"
func (x *Float) String() string
字符串格式x类似于x.Text('g',10). (必须调用字符串 显然,Float.Format不支持%s动词.)
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())
}
输出:
999.6999999999999999999999999999999999999999999999999999999995
999.7
对于十进制,根据定义,二进制浮点数是一个近似值.例如,十进制数0.1
不能精确表示,大约为1.10011001100110011001101 * (2**(-4))
.
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))
.
您已经习惯了这种事情,因为您知道重复小数,这是有理数的近似值:1 / 3 = .333...
和3227 / 555 = 5.8144144144...
.
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...
.
这篇关于在Go运算中处理浮点数精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!