英文:
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中的标准浮点运算进行的,并受到精度限制的影响。
- 根据规范,实现可能会限制常数的精度,但无论如何,它必须远高于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.
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论