問題描述
我正在讀取一個帶有浮點數的文本文件,所有這些都帶有 1 或 2 個小數點.我正在使用 float()
將一行轉換為浮點數,如果失敗則引發 ValueError
.我將所有浮點數存儲在一個列表中.打印出來時,我想將其打印為小數點后 2 位的浮點數.
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.
假設我有一個帶有數字 -3,65, 9,17, 1 的文本文件.我閱讀了每個文件,并將它們轉換為浮點數并將它們附加到列表中.現在在 Python 2 中,調用 float(-3.65)
會返回 -3.65
.然而,在 Python 3 中,float(-3.65) 返回
-3.6499999999999999`,這會失去其精度.
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.
我想打印浮點數列表,[-3.6499999999999999, 9.1699999999999999, 1.0]
僅包含 2 個小數點.按照 '%.1f' % round(n, 1)
的行做一些事情會返回一個字符串.如何返回浮點數的所有兩個小數點的列表,而不是字符串?到目前為止,我使用 [round(num, 2) for num in list]
對其進行了四舍五入,但需要設置小數點/精度而不是 round()
.
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()
.
推薦答案
一句話,你不能.
3.65
不能完全表示為 float
.您得到的數字是與 3.65
最接近的數字,具有精確的 float
表示.
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.
(舊的?)Python 2 和 3 之間的區別純粹是由于默認格式.
The difference between (older?) Python 2 and 3 is purely due to the default formatting.
我在 Python 2.7.3 和 3.3.0 中都看到了以下內容:
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'
有關精確的十進制數據類型,請參閱 decimal.Decimal
.
For an exact decimal datatype, see decimal.Decimal
.
這篇關于Python 3 浮點小數點/精度的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!