为什么 Golang 的 float64 乘法结果不一致?

huangapple go评论90阅读模式
英文:

Why golang's float64 multiplication results are inconsistent

问题

Golang的默认浮点类型是float64,但我得到了两个不同的结果:

1.005 * 100            // 100.5
float64(1.005) * 100   // 100.49

此外,我还遇到了另一个问题:

var n = 1.005
const m = 1.005
rn := n * n    // 1.01002499
rm := m * m    // 1.010025
t.Log(rn, rm)

有人可以解释一下吗?

英文:

Golang's default float type is float64, but I got two different results for:

1.005 * 100            // 100.5
float64(1.005) * 100   // 100.49

Besides, I got another problem:

var n = 1.005
const m = 1.005
rn := n * n    // 1.01002499
rm := m * m    // 1.010025
t.Log(rn, rm)

Anyone kindly explain it?

答案1

得分: 1

当将两个常数相乘时,数学计算是在编译时进行的,使用任意精度算术[1]。这意味着结果的精度可以比常规浮点运算更高,常规浮点运算是使用CPU中的标准浮点运算进行的,并受到精度限制的影响。

  1. 根据规范,实现可能会限制常数的精度,但无论如何,它必须远高于float32或float64的最大精度。
英文:

When multiplying 2 constants together, the math is done at compile time with arbitrary precision arithmetic[1]. This means that the result can have a higher accuracy than regular float operations, which are done with the standard floating point operations in your CPU and subject to precision limits.

  1. According to the spec, an implementation may limit the precision of constants, but in any case it must be well above the max precision of either float32 or float64.

huangapple
  • 本文由 发表于 2021年6月22日 14:16:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/68078438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定