为什么 Scala 不能为 Double 上的简单加法得到精确的答案?

Why Scala dose not get precise answer for simple addition on Double?

这种情况可以通过如下简单的一行来重现:

Scala version 2.11.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_66).

scala> 0.2+0.7
res0: Double = 0.8999999999999999

那么这背后的原因是什么? 如果中间过程产生一个结果,我如何测试答案是否正确 结果不准确?

谢谢。

这个问题更多地与数学如何与我们的处理器一起工作,而不是与 Scala 一起工作。

斯卡拉,

$ scala
Welcome to Scala 2.11.8 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_101).
Type in expressions for evaluation. Or try :help.

scala> 0.2 + 0.7
res0: Double = 0.8999999999999999

Python,

$ python
Python 2.7.12 (default, Jun 29 2016, 14:05:02) 
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> 0.2 + 0.7
0.8999999999999999

Node.js

$ node
> 0.2 + 0.7
0.8999999999999999