有人可以解释一下:0.2 + 0.1 = 0.30000000000000004? [英] Can someone explain this: 0.2 + 0.1 = 0.30000000000000004?
问题描述
为什么在 Python Interpreter 中会出现以下情况?
<预><代码>>>>0.1+0.1+0.1-0.35.551115123125783e-17>>>0.1+0.10.2>>>0.2+0.10.30000000000000004>>>0.3-0.30.0>>>0.2+0.10.30000000000000004>>>为什么不是0.2 + 0.1 = 0.3
?
那是因为 .1
不能以二进制浮点表示形式精确表示.如果你尝试
Python 将以 .1
响应,因为它只打印到一定的精度,但已经有一个小的舍入误差..3
也会发生同样的情况,但是当你发出
然后 .2
和 .1
中的舍入误差累积.另请注意:
Duplicates:
How is floating point stored? When does it matter?
Why does the following occur in the Python Interpreter?
>>> 0.1+0.1+0.1-0.3
5.551115123125783e-17
>>> 0.1+0.1
0.2
>>> 0.2+0.1
0.30000000000000004
>>> 0.3-0.3
0.0
>>> 0.2+0.1
0.30000000000000004
>>>
Why doesn't 0.2 + 0.1 = 0.3
?
That's because .1
cannot be represented exactly in a binary floating point representation. If you try
>>> .1
Python will respond with .1
because it only prints up to a certain precision, but there's already a small round-off error. The same happens with .3
, but when you issue
>>> .2 + .1
0.30000000000000004
then the round-off errors in .2
and .1
accumulate. Also note:
>>> .2 + .1 == .3
False
这篇关于有人可以解释一下:0.2 + 0.1 = 0.30000000000000004?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!