浮点数0.2 + 0.1舍入误差 [英] floating point 0.2 + 0.1 rounding error
问题描述
可能重复:
JavaScript的数学运算是否被破坏?
Possible Duplicate:
Is JavaScript's Math broken?
我遇到了这个四舍五入的问题:
I came across this rounding issue:
当我这样做时:
.2 + .1 results in 0.30000000000000004
.7 + .1 results in 0.7999999999999999
1.1 + .1 results in 1.2000000000000002
以此类推...
任何人都可以(详细解释)为什么吗?可能是一些二进制四舍五入的东西.但是我真的很想知道会发生什么...
Can anyone explain (in detail) why? Probably some binary rounding stuff. But I like to really know what happens...
推荐答案
简而言之,因为.2
实际上不是.2;它实际上是最接近的可表示双精度数,即
In a nutshell, because .2
isn't actually .2; it's actually the closest representable double-precision number, which is
0.200000000000000011102230246251565404236316680908203125.
类似地,.1
确实是
0.1000000000000000055511151231257827021181583404541015625
将它们加在一起时,结果会再次四舍五入到最接近的可表示数字
When you add those together, the result is rounded again to the nearest representable number, which is
0.3000000000000000444089209850062616169452667236328125
最后,当您将其打印出来时,该数字将四舍五入为17位十进制数字,从而得到您观察到的结果.
Finally, when you print it out, that number gets rounded to 17 decimal digits, giving the result you observe.
您的其他示例遵循相同的模式.
Your other examples follow the same pattern.
这篇关于浮点数0.2 + 0.1舍入误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!