python列表中的浮点偏差

时间:2011-09-10 21:30:54

标签: python floating-point rounding

  

可能重复:
  Python float - str - float weirdness

我在codepad.org上的python中运行以下代码:

num = 1.6
print num
list = [num]
print list
num2 = list[0]
print num2

我得到以下输出:

1.6
[1.6000000000000001]
1.6

为什么列表中的微小偏差?

1 个答案:

答案 0 :(得分:3)

list.__str__在其元素上调用repr,其中打印调用str

>>> str(1.6)
'1.6'
>>> repr(1.6)
'1.6000000000000001'

由于浮点数不能保证精确(并且对于整数a,b不能表示为* 2 b 的值不能精确),两种表示都是正确的,或者,换句话说:

>>> 1.6 == 1.6000000000000001
True