// In golang
x, y := big.NewFloat(26959535291011309493156476344723991336010898738574164086137773096960), big.NewFloat(14484.162361)
z := new(big.Float).Quo(x, y)
fmt.Println(fmt.Sprintf("%f", z))
output: 1861311315012765262390495455137379355146730679910059382988079104.000000
// In python
v1 = 26959535291011309493156476344723991336010898738574164086137773096960000000
v2= 14484162361
print v1/v2
output:1861311315012765306929610463010191006516769515973403833769533170
最佳答案
您在 Go 和 Python 中执行的操作不同。在 Go 中你除以 2 个 float ,而在 Python 中你除以 2 个整数。结果只是“大致”相等,因为您提供的输入数字失去了精度,而且浮点运算的精度也有限(不足)。
如果您在 Go 中执行相同的整数除法(使用 big.Int
类型),您会得到相同的结果:
i, ok := big.NewInt(0).SetString("26959535291011309493156476344723991336010898738574164086137773096960000000", 10)
if !ok {
panic("invalid")
}
j, ok := big.NewInt(0).SetString("14484162361", 10)
if !ok {
panic("invalid")
}
k := big.NewInt(0).Quo(i, j)
fmt.Println(k)
这个输出:
1861311315012765306929610463010191006516769515973403833769533170
如果您想在 Go 中执行浮点除法,请不要使用 float64
类型来表示您的输入,因为它们的精度有限。发生这种情况是因为您使用 big.NewFloat()
创建了输入数字它有一个 float64
类型的参数,所以你传递的常量将被隐式转换为 float64
并且你已经失去了精度。
改为使用 big.Float
类型,并将您的输入指定为 string
值并使用 Float.SetString()
进行设置;并手动提高精度(使用 Float.SetPrec()
)。如果这样做,您将得到“相同”的结果(整数部分相同,加上一些分数值):
x, ok := big.NewFloat(0).SetPrec(500).SetString("26959535291011309493156476344723991336010898738574164086137773096960")
if !ok {
panic("invalid")
}
y, ok := big.NewFloat(0).SetPrec(500).SetString("14484.162361")
if !ok {
panic("invalid")
}
z := new(big.Float).SetPrec(500).Quo(x, y)
fmt.Println(fmt.Sprintf("%f", z))
输出:
1861311315012765306929610463010191006516769515973403833769533170.518151
试试 Go Playground 上的例子.
请注意 Float.Quo()
的精度取决于:
Precision, rounding, and accuracy reporting are as for Add.
这是:
If z's precision is 0, it is changed to the larger of x's or y's precision before the operation. Rounding is performed according to z's precision and rounding mode; and z's accuracy reports the result error relative to the exact (not rounded) result.
关于python - 为什么 Go 和 Python 在除大数时返回不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49646574/