float deviation in python list [duplicate]

眉间皱痕 提交于 2019-12-12 02:08:37

问题


Possible Duplicate:
Python float - str - float weirdness

I run the following code in python on codepad.org:

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

And I get the following output:

1.6
[1.6000000000000001]
1.6

Why the tiny deviation in the list?


回答1:


list.__str__ calls repr on its elements, where as print calls str:

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

Since floating point numbers are not guaranteed to be exact (and cannot be exact for values that can't be expressed as a * 2b for integers a,b), both representations are correct, or, in other words:

>>> 1.6 == 1.6000000000000001
True


来源:https://stackoverflow.com/questions/7374836/float-deviation-in-python-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!