go - big.Float SetPrec 奇怪的行为

标签 go

在 golang 中使用 big.Float 进行一些计算后,我将精度设置为 2。

即使你的数字只是一个简单的 10,在设置精度后它是 8。

package main

import (
    "fmt"
    "math/big"
)

func main() {
    cost := big.NewFloat(10)
    fmt.Println("COST NOW", cost)

    perKWh := big.NewFloat(0)
    cost.Add(cost, perKWh)
    fmt.Println("COST ", cost.String())

    perMinute := big.NewFloat(0)
    cost.Add(cost, perMinute)
    fmt.Println("COST ", cost.String())

    discountAmount := big.NewFloat(0)
    cost.Sub(cost, discountAmount)
    floatCos, _ := cost.Float64()
    fmt.Println(fmt.Sprintf("COST FLOAT %v", floatCos))
    cost.SetPrec(2)

    fmt.Println("COST ", cost.String())
}

在此处检查 Playground 示例:https://play.golang.org/p/JmCRXkD5u49

想知道为什么

最佳答案

来自fine manual :

type Float
[...]
Each Float value also has a precision, rounding mode, and accuracy. The precision is the maximum number of mantissa bits available to represent the value. The rounding mode specifies how a result should be rounded to fit into the mantissa bits, and accuracy describes the rounding error with respect to the exact result.

big.Float 在内部表示为:

sign × mantissa × 2**exponent

当您调用 SetPrec 时您正在设置可用于尾数的位数,而不是数字的十进制表示中的精度位数。

您不能用两位尾数表示十进制 10(二进制 1010),因此它四舍五入为可以放入 2 位的十进制 8(二进制 1000)。您至少需要三位来存储十进制 10 的 101 部分。8 可以放入一个尾数中,因此如果您说 cost.SetPrec(1 )

使用大包时,您需要考虑二进制。

关于go - big.Float SetPrec 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819612/

相关文章:

javascript - Go 语言中的正则表达式 "before text matching"

json - 如何使用 Go 从 JSON 文件中读取一个值

go - 如何等到缓冲 channel (信号量)为空?

arrays - GOLang 解码 JSON(未拾取简单数组)

mongodb - 来自 MongoDB 的 alpha 驱动程序的简单 CRUD 示例

Golang mongo-go-driver Beta 1,使用大于运算符

go - 多个返回值和 := in go

arrays - Goroutines 共享 slice : : trying to understand a data race

arrays - 使用非UTF-8编码的字符串作为映射键

time - 如何获取两个日期之间的小时差