我对此完全感到困惑。
从下面开始
import numpy as np a = np.array([4, -9]) a[0] = 0.4 a我预期的输出: array([0.4,-9])。但这给了我
array([0,-9])。
但是当我将 dtype 更改为 f
a = np.array([4, -9], 'f') a[0] = 0.4 a它给了我 array([0.40000001,-9。],dtype = float32)
numpy.array(object,dtype = None,copy = True,order ='的文档K',subok = False,ndmin = 0)说:
dtype:数据类型,可选数组的所需数据类型。如果未给出,则将类型确定为在序列中保存对象所需的最小类型。此参数只能用于上载阵列。对于向下转换,请使用.astype(t)方法。
dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.
当我初始化数组时,它将值初始化为整数,所以当我用 float 为数组建立索引时,它只能识别整数 0.4 的一部分,因此给了我 0 。这就是我的理解。这样对吗?。但是我仍然对这种行为感到惊讶。
When I initialized the array it initialized the values to integers and so when I indexed the array with a float it only recognized the integer part of 0.4 and hence gave me 0. This is how I understand it. Is this correct?. But I am still surprised by this behavior.
问题:这到底是怎么回事?
Question: What exactly is going on here?
推荐答案问题是您的数组为 dtype = np.int64 :
In [141]: a = np.array([4, -9]) In [142]: a.dtype Out[142]: dtype('int64')这意味着您只能存储整数,并且所有浮点数都会在分配完成之前被截断。如果要将浮点数和整数存储在一起,则应首先指定 dtype = object :
This means that you can only store integers, and any floats are truncated before assignment is done. If you want to store floats and ints together, you should specify dtype=object first:
In [143]: a = np.array([4, -9], dtype=object) In [144]: a[0] = 0.4 In [145]: a Out[145]: array([0.4, -9], dtype=object)关于 array([0.40000001,-9。] , 0.4 ,因为浮点数在内存中没有确切的表示形式(只有一个近似值),这说明了您看到的不精确性。
As for the issue with array([ 0.40000001, -9. ], 0.4, as a floating point number does not have an exact representation in memory (only an approximate one), which accounts for the imprecision you see.
更多推荐
带有和不带有dtype的numpy.array行为很奇怪
发布评论