所以这只是浪费了我几个小时的调试时间..
a,b = 32980.642295,32630.642295
print a-b
print int(a-b)
print int(a) - int(b)
输出:
350.0
349
350
谁能给我解释一下这是怎么回事?为什么 350.0 的 int 不只是 350?我假设 python 在转换为 int 之前在转换 a 和 b 时做了一些奇怪的事情..
编辑/更新:
x = a-b
存储在 x 中的值现在是 349.99999999999636 而不是 350.0
这可能有助于 future 的人来发帖 Is floating point math broken?
请您参考如下方法:
print 隐式地将 str() 应用于要求打印的内容,在 Python 2 中,str(some_float) 舍入到 12 个有效位数字。 repr(some_float) 四舍五入到 17:
>>> a,b = 32980.642295,32630.642295
>>> print str(a-b)
350.0
>>> print repr(a-b)
349.99999999999636
原来如此。 a-b 实际上比 350 小一点。
在 Python 3 中,str(some_float) 和 repr(some_float) 都生成最短的字符串 s 使得 eval( s) == some_float:
# Python 3 here, not Python 2
>>> a,b = 32980.642295,32630.642295
>>> print(str(a-b))
349.99999999999636
>>> print(repr(a-b))
349.99999999999636
>>> eval(str(a-b)) == a-b
True
