2

在 Python 中,使用 numpy,在迭代过程中打印它们的值会发生变化,或者打印整个数组,为什么以及如何解决这个问题?我希望它们是例如 0.8 而不是 0.799999999 ...

>>> import numpy as np
>>> b = np.arange(0.5,2,0.1)
>>> for value in b:
...     print(value)
... 
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999
1.0999999999999999
1.1999999999999997
1.2999999999999998
1.4
1.4999999999999998
1.5999999999999996
1.6999999999999997
1.7999999999999998
1.8999999999999997
>>> print(b)
[0.5 0.6 0.7 0.8 0.9 1.  1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9]
>>> 
4

4 回答 4

3

发生这种情况是因为 Python 和 NumPy 使用浮点运算,其中某些数字(即 0.1)无法精确表示。还要检查python 浮点问题和限制

您可以为此使用 Numpy 的 np.around :

>> b = np.around(b, 1) # first arg is the np array, second arg is the no. of decimal points
>> for value in b:
      print(value)

0.5
0.6
0.7
0.8
0.9
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
于 2020-02-24T11:29:26.153 回答
1

要打印,您可以使用 print format-"%.1f"

>>> for value in b:
...      print("%.1f" %value)
...
0.5
0.6
0.7
0.8
0.9
1.0
1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
于 2020-02-24T11:40:14.480 回答
0

你可以用round来得到整数

for value in b:
       print(round(value,2))
于 2020-02-24T11:32:17.213 回答
0

我认为,__str__ndarray 的方法是以这种方式实现的。这种行为没有什么奇怪的——当你使用

print(b)

调用该函数__str__是为了可读性。在此调用期间,您对 ndarray 进行操作。当您在 for 循环中进行打印时,您使用__str__浮点数,它会按原样打印数字。

希望这很清楚,但这实际上会有所帮助。

:)

于 2020-02-24T11:44:56.750 回答