如果我在 python2.7 控制台上运行以下命令,它会给我输出:
>>> 1.2 - 1.0
0.19999999999999996
>>> print 1.2 - 1.0
0.2
当我在 python3.5.2 中运行相同的操作时
>>> 1.2 - 1.0
0.19999999999999996
>>> print(1.2 - 1.0)
0.19999999999999996
我想知道为什么在 python2.7.12 打印语句中只给我 0.2 但在 python3.5.2 打印函数中给我 0.19999999999999996。
这不是由于print
的变化,而是floats
的__str__
函数的变化,打印隐式调用。因此,当您打印时,它会发出如下调用:
# For Python 2.7
>>> print (1.2 - 1.0).__str__()
0.2
为了按原样显示 float 值,您可以显式调用 .__repr__
为:
>>> print (1.2 - 1.0).__repr__()
0.19999999999999996
更多详情,查看Martjin's answer on Floating point behavior in Python 2.6 vs 2.7其中指出:
In Python 2.7 only the representation changed, not the actual values. Floating point values are still binary approximations of real numbers, and binary fractions don't always add up to the exact number represented.