在Python列表中浮动偏差 [英] float deviation in python list

查看:146
本文介绍了在Python列表中浮动偏差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

Python浮动 - str - 浮动怪异


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

  num = 1.6 
print num
list = [num ]
打印列表
num2 =列表[0]
打印num2



< p $>

  1.6 
[1.6000000000000001]
1.6

为什么在列表中的偏差很小?

解决方法

list .__ str __ 调用 repr $ c> str

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

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

 >>> 1.6 == 1.6000000000000001 
True


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?

解决方案

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

这篇关于在Python列表中浮动偏差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆