[英]The problem that Precision loss in big.Float
While running: 在跑步的时候:
package main
import (
"fmt"
"math/big"
)
func main() {
a := big.NewFloat(float64(2.1234))
fmt.Println(a.Text(102,18))
}
I expected 2.123400000000000000 as output, but instead got 2.123400000000000176. 我期望输出为2.123400000000000000,但是得到了2.123400000000000176。
Can someone explain me why I do not have the expected number? 有人可以向我解释为什么我没有预期的人数吗?
big.NewFloat(float64(2.1234))
float64(2.1234)
converts to Go float64
(IEEE-754 64-bit floating-point), which has 53 bits of precision. float64(2.1234)
转换为Go float64
(IEEE-754 64位浮点数),其精度为53位。
For example, 例如,
package main
import (
"fmt"
"math/big"
)
func main() {
// 53 bits of precision (float64)
a := big.NewFloat(float64(2.1234))
fmt.Println(a.Text(102, 18))
x := "2.1234"
// 53 bits of precision
f, _, err := big.ParseFloat(x, 10, 53, big.ToNearestEven)
if err != nil {
panic(err)
}
fmt.Println(f.Text(102, 18))
// 256 bits of precision
f, _, err = big.ParseFloat(x, 10, 256, big.ToNearestEven)
if err != nil {
panic(err)
}
fmt.Println(f.Text(102, 18))
}
Playground: https://play.golang.org/p/z5iK90lQcD9 游乐场: https : //play.golang.org/p/z5iK90lQcD9
Output: 输出:
2.123400000000000176
2.123400000000000176
2.123400000000000000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.