python - 为什么 Python3 中的 print 函数要对小数进行四舍五入?

标签 python python-2.7 python-3.x

<分区>

如果我在 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.

关于python - 为什么 Python3 中的 print 函数要对小数进行四舍五入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41235183/

相关文章:

python - Pandas 数据框按日期范围过滤 : today - today+ 1 year

python - Django 多个数据库 - 关系不存在;第 1 行 : SELECT COUNT(*) AS "__count" FROM

python - Numpy 因 python-dbg( undefined symbol : Py_InitModule4_64)

python - 最小化余弦距离 theano

python - 根据数据类型从 DataFrame 中删除列

python - 从Python到MySQL上传数据失败

python - 通常的技巧并不能解决 Django 中的 "expected string or bytes-like object"

python - 根据相同的索引连接两个列表

python - 为什么即使没有要打印的数据,打印命令也会换行

python - 创建类似文件的对象作为数据缓冲区