Python 3浮点小数点/精度 [英] Python 3 Float Decimal Points/Precision

查看:217
本文介绍了Python 3浮点小数点/精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取带有浮点数的文本文件,全部使用1或2个小数点。我使用 float()将一行转换为一个浮点数,如果失败则引发一个 ValueError 。我将所有的花车存储在一个列表中。打印出来的时候,我想把它打印成小数点后2位。

9,17,1.我读了每一个,一旦我将它们转换为浮动,并将它们追加到列表中。现在在Python 2中,调用 float(-3.65)返回 -3.65 。然而,在Python 3中, float(-3.65)返回 -3.6499999999999999`,这就失去了它的精度。



打印浮点数列表, [ - 3.6499999999999999,9.1699999999999999,1.0] 只有2个小数点。沿着'%。1f'%round(n,1)的方向做一些事情会返回一个字符串。我如何返回浮点数的所有两个小数点的列表,而不是字符串?到目前为止,我已经使用 [round(num,2)for num in list] 对其进行了四舍五入,但是需要设置小数点/精度而不是 round()

解决方案

b
$ b

3.65 不能完全表示为 float 。您得到的数字是距离 3.65 最近的数字,具有精确的 float 表示形式。



Python 2和3之间的差异纯粹是由于默认的格式化。



我看到以下在Python 2.7.3和3.3.0中:

  In [1]:3.65 
Out [1]: 3.65

In [2]:'%.20f'%3.65
Out [2]:'3.64999999999999991118'

有关精确的十进制数据类型,请参阅 decimal.Decimal


I am reading a text file with floating point numbers, all with either 1 or 2 decimal points. I am using float() to convert a line into a float, and raising a ValueError if that fails. I am storing all floats in a list. When printing it out, I'd like to print it out as a 2 decimal places floating point.

Assume I have a text file with the numbers -3,65, 9,17, 1. I read each one, and once I convert them to float and append them to a list. Now in Python 2, calling float(-3.65) returns -3.65. In Python 3 however, float(-3.65) returns-3.6499999999999999` which loses its precision.

I want to print the list of floats, [-3.6499999999999999, 9.1699999999999999, 1.0] with 2 decimal points only. Doing something along the lines of '%.1f' % round(n, 1) would return a string. How can I return a list of all two decimal points of floats, and not strings? So far, I rounded it using [round(num, 2) for num in list] but would need to set the decimal points / precision instead of round().

解决方案

In a word, you can't.

3.65 cannot be represented exactly as a float. The number that you're getting is the nearest number to 3.65 that has an exact float representation.

The difference between (older?) Python 2 and 3 is purely due to the default formatting.

I am seeing the following both in Python 2.7.3 and 3.3.0:

In [1]: 3.65
Out[1]: 3.65

In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'

For an exact decimal datatype, see decimal.Decimal.

这篇关于Python 3浮点小数点/精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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